I have one split view controller and i am presenting a popover inside it. Now when the device orientation is changing from landscape to portrait i have to run a piece of code & if it is changing from portrait to landscape i have to run another piece of code. How to achieve this in Swift.
Asked
Active
Viewed 1.4k times
2 Answers
18
Updated to Swift 4:
Add below code in ViewDidLoad
:
NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged), name: Notification.Name("UIDeviceOrientationDidChangeNotification"), object: nil)
Then, create one function like below
@objc func orientationChanged() {
if(UIDeviceOrientationIsLandscape(UIDevice.current.orientation)){
print("landscape")
}
if(UIDeviceOrientationIsPortrait(UIDevice.current.orientation)){
print("Portrait")
}
}
Hope this will helps you :)

iVarun
- 6,496
- 2
- 26
- 34
-
1UIDeviceOrientation != UIInterfaceOrientation – nnrales Jan 06 '18 at 15:43
1
From iOS 8.0 You can detect the orientation change using below method.
In objective-c
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
in swift
func viewWillTransitionToSize(_ size: CGSize,
withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)
from the size you can find out.

Surjeet Rajput
- 1,251
- 17
- 24
-
-
**UISplitViewContoller** is also a subclass of **UIVIewController** .It should be called. One more important point check ur calling this method with super or not.The **viewWillTransitionToSize:withTransitionCoordinator:** seems to only work if the interface is actually going to change size, meaning we have rotated 90 degrees. If you have a mask on your layout that only allows landscape, when rotation 180 degrees, the interface size doesn't change, so this method doesn't seem to be called. – Surjeet Rajput Apr 14 '16 at 06:45