I need to detect when the device is in portrait orientation so that I can fire off a special animation. But I do not want my view to autorotate.
How do I override a
.UIDeviceOrientationDidChange notification is called many times on iphone even when device did not rotate. Do not know the reason, but if you need it only when device really rotated, then do the following.
NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged), name: .UIDeviceOrientationDidChange, object: nil)
The method called from observer should look like this:
func orientationChanged() {
if traitCollection.isIphone {
defer {
self.previousTraitCollectionForIphone = traitCollection
}
guard let previousTraitCollectionForIphone = previousTraitCollectionForIphone else {
updateView()
return
}
if previousTraitCollectionForIphone != traitCollection {
updateView()
}
} else {
updateView()
}
}