[英]Detect iOS device orientation change without rotating view
我有一个 UIViewController,我想检测该 ViewController 上的设备方向变化。 但我不想旋转视图。 我的应用程序支持所有方向,但此 ViewController 应始终保持纵向模式。
我可以将supportedInterfaceOrientations
设置为 portrait only 以获得所需的功能。 但我仍然想知道这个 ViewController 中的方向变化。 通常我可以使用viewWillTransition
方法或traitCollectionDidChange
方法获取事件。 但是当我将supportedInterfaceOrientations
设置为 portrait 时,这些方法都不会被调用。
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
// this method never get called
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
}
当我将supportedInterfaceOrientations
设置为仅纵向时,有没有办法检测设备方向的变化?
我想你可以订阅通知
final class ViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, #selector(handleOrientationChange, name: UIDevice.orientationDidChangeNotification, object: nil))
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc
private func handleOrientationChange() {
// Yay, orientation changed!
}
}
这是一种方法。
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
// return UIInterfaceOrientationMask.all } else{ }
return self.orientationLock
}
然后对于 viewController,您要更改允许的所需方向
AppDelegate.AppUtility.lockOrientation(.portrait, andRotateTo: .portrait)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.