我正在尝试检测某个 ViewController 中的方向变化。我使用通知和自定义功能。对于 iPhone 7(运行 iOS 10.2),每次通知更改时都会调用旋转功能。但是在使用 iPhone 6(运行 9.3)或 iPhone 6s(运行 10.0)时,该函数仅在屏幕加载时被调用一次,但在我转动手机时不会被调用。
代码:
func rotated() {
if UIDevice.current.orientation.isLandscape {
print("Landscape")
} else {
print("Portrait")
}
}
override func viewDidLoad() {
super.viewDidLoad()
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
最佳答案
在 viewWillAppear
函数中设置通知,它应该可以正常工作。在模拟器上可用的设备上对我来说工作正常。实际上,当 View Controller 第一次出现时, View DidLoad 函数只被调用一次。而 View 将在每次加载 View Controller 时调用。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
关于ios - UIDeviceOrientation DidChange 仅适用于 iPhone 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41877362/