How to detect orientation change?
Here's how I got it working:
In AppDelegate.swift
inside the didFinishLaunchingWithOptions
function I put:
NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.rotated), name: UIDevice.orientationDidChangeNotification, object: nil)
and then inside the AppDelegate class I put the following function:
func rotated() {
if UIDeviceOrientationIsLandscape(UIDevice.current.orientation) {
print("Landscape")
}
if UIDeviceOrientationIsPortrait(UIDevice.current.orientation) {
print("Portrait")
}
}
Hope this helps anyone else!
Thanks!
Using -orientation
property of UIDevice
is not correct (even if it could work in most of cases) and could lead to some bugs, for instance UIDeviceOrientation
consider also the orientation of the device if it is face up or down, there is no direct pair in UIInterfaceOrientation
enum for those values.
Furthermore, if you lock your app in some particular orientation, UIDevice will give you the device orientation without taking that into account.
On the other side iOS8 has deprecated the interfaceOrientation
property on UIViewController
class.
There are 2 options available to detect the interface orientation:
- Use the status bar orientation
- Use size classes, on iPhone if they are not overridden they could give you a way to understand the current interface orientation
What is still missing is a way to understand the direction of a change of interface orientation, that is very important during animations.
In the session of WWDC 2014 "View controller advancement in iOS8" the speaker provides a solution to that problem too, using the method that replaces -will/DidRotateToInterfaceOrientation
.
Here the proposed solution partially implemented, more info here:
func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
let orientation = orientationFromTransform(coordinator.targetTransform())
let oldOrientation = UIApplication.sharedApplication().statusBarOrientation
myWillRotateToInterfaceOrientation(orientation,duration: duration)
coordinator.animateAlongsideTransition({ (ctx) in
self.myWillAnimateRotationToInterfaceOrientation(orientation,
duration:duration)
}) { (ctx) in
self.myDidAnimateFromInterfaceOrientation(oldOrientation)
}
}
I need to detect rotation while using the camera with AVFoundation
, and found that the didRotate
(now deprecated) & willTransition
methods were unreliable for my needs. Using the notification posted by David did work, but is not current for Swift 3.x & above.
The following makes use of a closure, which appears to be Apple's preference going forward.
var didRotate: (Notification) -> Void = { notification in
switch UIDevice.current.orientation {
case .landscapeLeft, .landscapeRight:
print("landscape")
case .portrait, .portraitUpsideDown:
print("Portrait")
default:
print("other (such as face up & down)")
}
}
To set up the notification:
NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification,
object: nil,
queue: .main,
using: didRotate)
To tear down the notification:
NotificationCenter.default.removeObserver(self,
name: UIDevice.orientationDidChangeNotification,
object: nil)
Regarding the deprecation statement, my initial comment was misleading, so I wanted to update that. As noted, the usage of @objc
inference has been deprecated, which in turn was needed to use a #selector
. By using a closure instead, this can be avoided and you now have a solution that should avoid a crash due to calling an invalid selector.
According to the Apple docs:
This method is called when the view controller's view's size is changed by its parent (i.e. for the root view controller when its window rotates or is resized).
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if UIDevice.current.orientation.isLandscape {
print("Landscape")
}
if UIDevice.current.orientation.isFlat {
print("Flat")
} else {
print("Portrait")
}
}