如何在 iPad 中检查设备方向从纵向到横向的变化,反之亦然
How to check Device Orientation Change From Portrait To Landscape and Vice-Versa in iPad
我有一个拆分视图控制器,我正在其中显示一个弹出窗口。现在,当设备方向从横向变为纵向时,我必须 运行 一段代码 & 如果它从纵向变为横向,我必须 运行 另一段代码。如何在 Swift.
中实现这一点
已更新为 Swift 4:
在 ViewDidLoad
中添加以下代码:
NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged), name: Notification.Name("UIDeviceOrientationDidChangeNotification"), object: nil)
然后,创建一个如下所示的函数
@objc func orientationChanged() {
if(UIDeviceOrientationIsLandscape(UIDevice.current.orientation)){
print("landscape")
}
if(UIDeviceOrientationIsPortrait(UIDevice.current.orientation)){
print("Portrait")
}
}
希望这对您有所帮助:)
来自iOS 8.0 您可以使用以下方法检测方向变化。
在objective-c
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
在swift
func viewWillTransitionToSize(_ size: CGSize,
withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)
从尺码就可以知道了。
我有一个拆分视图控制器,我正在其中显示一个弹出窗口。现在,当设备方向从横向变为纵向时,我必须 运行 一段代码 & 如果它从纵向变为横向,我必须 运行 另一段代码。如何在 Swift.
中实现这一点已更新为 Swift 4:
在 ViewDidLoad
中添加以下代码:
NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged), name: Notification.Name("UIDeviceOrientationDidChangeNotification"), object: nil)
然后,创建一个如下所示的函数
@objc func orientationChanged() {
if(UIDeviceOrientationIsLandscape(UIDevice.current.orientation)){
print("landscape")
}
if(UIDeviceOrientationIsPortrait(UIDevice.current.orientation)){
print("Portrait")
}
}
希望这对您有所帮助:)
来自iOS 8.0 您可以使用以下方法检测方向变化。
在objective-c
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
在swift
func viewWillTransitionToSize(_ size: CGSize,
withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)
从尺码就可以知道了。