How to observe device orientation changes in Swift

Oscar de la Hera Gomez
A flower that represents Swift next to one that represents XCode.  Beneath them sits the text "Orientation Changes."

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.

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.

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.

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.

Run the app on XCode and as you should rotate it, the orientation should be printed on the console.

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details