Reputation: 125
I need to have the correct width when rotating the device. I check the value and it works fine to update the value when rotating, except it gives me the width of the device reversed. So when I turn landscape, it gives me the width of the device in portrait and vice versa. Is there any solution to this?
For example UIScreen.main.bounds.size.width with an iPad in landscape gives me width 810.0 and in portrait: 1080.0.
Thanks!
var widthConstant: CGFloat = UIScreen.main.bounds.size.width
// Override view did load function
override func viewDidLoad() {
super.viewDidLoad()
...
// Rotation detection
NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: UIDevice.orientationDidChangeNotification, object: nil)
}
// Remove the rotation detection when deinitializing
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func rotated() {
// Update the view again after rotating
widthConstant = UIScreen.main.bounds.size.width
self.widthAnchorConstraint = tableView?.widthAnchor.constraint(equalToConstant: widthConstant)
print("WIDTH:", widthConstant)
}
Output:
WIDTH: 1080.0 (device is turned portrait)
WIDTH: 810.0 (device is turned landscape)
Upvotes: 0
Views: 899