Reputation: 1363
I am trying to detect the orientation change in a certain ViewController. I use the notification and a custom function. With iPhone 7 (running iOS 10.2) every time the notification changes the rotated function is being called. But while using iPhone 6 (running 9.3) or iPhone 6s (running 10.0) the function is being called only once, when the screen loads, but not when I turn around the phone.
Code:
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)
}
Upvotes: 1
Views: 1122
Reputation: 5467
Set up the notification in the viewWillAppear
function and it should work just fine. Works fine for me on devices available on the simulator. Actually the view DidLoad function is called only once when the view controller appears for the first time. Whereas the view will appear will be called everytime the view controller is about to be loaded.
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)
}
Upvotes: 1