How to check the change in device orientation from portrait to landscape and vice versa

I have one split view controller and I present it inside. Now that the device’s orientation changes from landscape to portrait, I have to run a piece of code, and if it changes from portrait to landscape, I need to run another piece of code. How to achieve this in Swift.

+5
source share
2 answers

From iOS 8.0, you can detect a change in orientation using the method below.

In objective-c

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator 

in quick

 func viewWillTransitionToSize(_ size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) 

on the size you can find out.

-1
source

Updated to Swift 4: Add the code below to ViewDidLoad :

 NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged), name: Notification.Name("UIDeviceOrientationDidChangeNotification"), object: nil) 

Then create one function as below

 @objc func orientationChanged() { if(UIDeviceOrientationIsLandscape(UIDevice.current.orientation)){ print("landscape") } if(UIDeviceOrientationIsPortrait(UIDevice.current.orientation)){ print("Portrait") } } 

Hope this helps you :)

+16
source

Source: https://habr.com/ru/post/1247014/


All Articles