I'm making an app where the iPad can be used in both landscape and portrait mode. The configuration of my UIViewControllers is the following :
I have a UIViewController
with a UICollectionView
which has the following constraints : top, leading, trailing, and bottom set to 0 with its superview (the superview is the UIView
of my UIViewController
).
When I tap a cell, I push another UIViewController
in the UINavigationController
which is a detail viewController of the cell. Simple.
When I change the device orientation in the first view controller, the UICollectionView
bounds are set properly.
Here come my problem :
If I select a cell in the UICollectionView
, the second detail viewController is displayed. Then if in this second ViewController I change the device orientation and then I go back into the first viewController, the view of my UIViewController
hasn't been rotated. I don't know why, I tried this without success :
self.view.layoutIfNeeded()
in viewDidAppear()
of my firstViewController to update constraints according the current orientation, it didn't work. This didn't work because I noticed one thing :
The frame view of my first viewController is still the same as the previous orientation, it didn't change... But if I rotate again the device, the UIViewController
detect the orientation changes, and the view bounds are set properly.
So my problem is : when I'm in the second view controller, and that I'm rotating the device, and then that I go back in the previous view controller, the previous controller hasn't detected the orientation change I just made in the second view controller.
GIF Demo :
After that I made a rotation from portrait to landscape mode, the view is not changed as the debug view hierarchy tool shows below :
The UIView
is still in portrait, so the UICollectionView
constraint's can't be updated with the new orientation...
Any ideas?
Resolved by resetting the frame of the view in my first viewController with the screen bounds in the viewWillAppear
method :
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.view.frame = UIScreen.main.bounds
self.view.layoutIfNeeded()
}
Like that the main UIView of my viewController have the right frame, and the constraints can be updated automatically when I call layoutIfNeeded()
on my UIView.
Found need to reset the frame size of collectionview. add self.collectionview.frame.size = size
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if let layout = self.collectionview.collectionViewLayout as? UICollectionViewFlowLayout {
let width = (size.width - 30) / 3
layout.itemSize = CGSize(width:width, height:width)
self.collectionview.frame.size = size
layout.invalidateLayout()
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.