I have a UIViewController and I wanna detect the device orientation changes on that ViewController. But I do not want to rotate the view. My app supports all orientations but this ViewController should keep portrait mode all the time.
I can set supportedInterfaceOrientations
to portrait only to get the desired functionality. But I still wanna know the orientation changes within this ViewController. Normally I can get the event with the viewWillTransition
method or traitCollectionDidChange
method. But when I set supportedInterfaceOrientations
to portrait none of those methods get called.
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)
}
Is there a way to detect the device orientation changes when I set supportedInterfaceOrientations
to portrait only?
CodePudding user response:
I think you can subscribe to a notification
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!
}
}