UIView frame not updating after orientation change
Add this function and you´ll detect the orientation change:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation.isLandscape {
print("Landscape")
} else if UIDevice.current.orientation.isPortrait {
print("Portrait")
}
}
To get orientation change callback you need to add this Notification
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
and you need to implement this method
func rotated() {
if(UIDeviceOrientationIsLandscape(UIDevice.current.orientation))
{
print("landscape")
}
if(UIDeviceOrientationIsPortrait(UIDevice.current.orientation))
{
print("Portrait")
}
}
The above accepted answer returns frame size before transition.So your view is not updating..You need to get the frame size after the transition has been completed.
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) -> Void in
let orient = UIApplication.shared.statusBarOrientation
switch orient {
case .portrait:
print("Portrait")
case .landscapeLeft,.landscapeRight :
print("Landscape")
default:
print("Anything But Portrait")
}
}, completion: { (UIViewControllerTransitionCoordinatorContext) -> Void in
//refresh view once rotation is completed not in will transition as it returns incorrect frame size.Refresh here
})
super.viewWillTransition(to: size, with: coordinator)
}