Swift version: 5.10
If your app needs to know the orientation of the user’s device – face up or face down – it takes only four steps to implement.
First, write a method that can be called when the device orientation changes:
@objc func orientationChanged() {
}
That needs to be marked @objc
because it’s going to be called by the system whenever the accelerometer signals the orientation has changed. So, step two is to request those changes be sent to the new method:
NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged), name: UIDevice.orientationDidChangeNotification, object: nil)
Third, ask the system to start checking for orientation changes:
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
You shouldn’t leave that on all the time unless you need it; you should call endGeneratingDeviceOrientationNotifications()
when you’re done with the data.
Finally, you can read the orientation
property of the current UIDevice
to see what the orientation currently is. This property doesn’t work correctly unless you already asked UIKit to begin generating device orientation notifications, which is why the above steps were required:
if UIDevice.current.orientation == .faceDown {
// it's face down
}
You probably want that inside orientationChanged()
so that it reads values as they change.
SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 2.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.