How to check Device Orientation Change From Portrait To Landscape and Vice-Versa in iPad [duplicate]

南笙酒味 提交于 2019-12-10 14:12:18

问题


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



来源:https://stackoverflow.com/questions/36591700/how-to-check-device-orientation-change-from-portrait-to-landscape-and-vice-versa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!