How to observe device orientation changes in Swift
![Oscar de la Hera Gomez](https://www.delasign.com/CDN/headshots/profile.webp)
![A flower that represents Swift next to one that represents XCode. Beneath them sits the text "Orientation Changes."](https://www.delasign.com/CDN/images/How-to-observe-device-orientation-changes-in-Swift.webp)
A step by step iOS tutorial on detecting when an iPhone or iPad changes orientation in Swift.
The following tutorial uses our Open Source Swift project to walk you through how to detect changes in orientation on an iPhone or iPad.
If you are looking for a tutorial that considers both device orientation changes as well as changes in the screen size to change layouts on MacOS or when multitasking on iPads, consult the tutorial in the link below.
We recommend that you clone our Open Source Swift Starter Project, checking out the main branch and carrying out the steps below. The changes can be found on the tutorial/device-orientation-observer branch.
git clone git@github.com:delasign/swift-starter-project.git
Step One: Begin observing UIDeviceChanges
![A screenshot of Xcode with a highlight on UIDevice.current.beginGeneratingDeviceOrientationNotifications() within the init function of the CustomUIView.swift file.](https://www.delasign.com/CDN/images/Begin.webp)
In CustomUIView.swift, in the init function, add the following line to begin to listen to orientation updates.
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
Step Two: Add the Notification Observer
![A screenshot of Xcode with a highlight on the observer that was added within the CustomUIView+Notifications.swift file.](https://www.delasign.com/CDN/images/Add-Observer.webp)
In CustomUIView+Notifications.swift, add a new Notification observer using the line below.
Please note that as part of our Open Source start project, CustomUIView initiates the notifications in the init function.
NotificationCenter.default.addObserver(self, selector: #selector(self.onOrientationChange), name: UIDevice.orientationDidChangeNotification, object: nil)
Step Three: Add the Notification selector
![A screenshot of Xcode with a highlight on the function that was added to the CustomUIView+Notifications.swift file.](https://www.delasign.com/CDN/images/Add-Selector.webp)
In CustomUIView+Notifications.swift, add a the selector using the code below.
Step Four: Verify
![A screenshot of XCode with a highlight on the console showing the results of this tutorial.](https://www.delasign.com/CDN/images/Verify_2023-02-12-010444_xtvn.webp)
Run the app on XCode and as you should rotate it, the orientation should be printed on the console.