斯威夫特 4.2
class ViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: UIDevice.orientationDidChangeNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func deviceOrientationDidChange() {
print(UIDevice.current.orientation.rawValue)
}
}
斯威夫特 3.0
我希望有人能迅速写下这个。我知道这是一个 Obj-C 帖子,但我没有找到类似的快速帖子,所以你去吧:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func deviceOrientationDidChange() {
print(UIDevice.current.orientation.rawValue)
}
}