How to detect orientation change after it happened using Swift 3?
I need to detect it after change to calculate frame size.
EDIT
I asked this question because I need to redraw view on orientation change like in this question: Can't get background gradient to fill entire screen upon rotation
I don't know how to implement answer that is marked as a correct answer.
I tried another answer
self.backgroundImageView.layer.sublayers?.first?.frame = self.view.bounds
but it's not working.
In viewDidLoad()
I have
let color1 = UIColor(red: 225.0/255.0, green: 210.0/255.0, blue: 0.0/255.0, alpha: 1.0).cgColor
let color2 = UIColor(red: 255.0/255.0, green: 125.0/255.0, blue: 77.0/255.0, alpha: 1.0).cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [color1, color2]
gradientLayer.locations = [ 0.0, 1.0]
gradientLayer.frame = self.view.bounds
self.view.layer.insertSublayer(gradientLayer, at: 0)
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)
}
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")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With