How to check Device Orientation Change From Portra

2019-06-20 09:03发布

问题:

This question already has an answer here:

  • How to detect orientation change? 21 answers

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.

回答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.



回答2:

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 :)