I am using Swift and I want to be able to load a UIViewController when I rotate to landscape, can anyone point me in the right direction?
I Can't find anything online and a little bit confused by the documentation.
I am using Swift and I want to be able to load a UIViewController when I rotate to landscape, can anyone point me in the right direction?
I Can't find anything online and a little bit confused by the documentation.
Need to detect rotation while using the camera with
AVFoundation
, and found that thedidRotate
(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/4.x.Swift 4.2 The notification name has been changed.
The closure value remains the same as Swift 4.0:
To set up the notification for Swift 4.2:
To tear down the notification for Swift 4.2:
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.Everything below here is obsolete as of XCode 10 & iOS 4.2
Swift 4.0 With Swift 4.0, Apple has encouraged us to avoid using the
#selector
, so this approach uses a completion block now. This approach is also backwards compatible with Swift 3.x & would be the recommended approach going forward.This is the compiler warning you will receive in a Swift 4.x project if you use the
#selector
function due to the deprecation of@objc
inference:Entry in swift-evolution on this change.
Setup the callback:
Setup the notification:
Tear it down:
For Swift 3
NOTE: Just use this code to identify UIViewController is in which orientation
I know this question is for
Swift
, but since it's one of the top links for a Google search and if you're looking for the same code inObjective-C
:Using
-orientation
property ofUIDevice
is not correct (even if it could work in most of cases) and could lead to some bugs, for instanceUIDeviceOrientation
consider also the orientation of the device if it is face up or down, there is no direct pair inUIInterfaceOrientation
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 onUIViewController
class.There are 2 options available to detect the 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: