问题
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