Reputation: 2045
In order to handle rotation In my app, I am using the following method:
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
collectionView2.collectionViewLayout.invalidateLayout()
let pageControl = UIPageControl()
let indexPath = IndexPath(item: pageControl.currentPage, section: 0)
DispatchQueue.main.async {
self.collectionView2.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
self.collectionView2.reloadData()
}
}
Now, the thing is, when I am running the app on a IPhone device, the method is triggered perfectly and the Layout is not affected by the rotation.
However, when I run it on an iPad and I rotate to landscape, the layout is not managing to center the ui content [in my case a collectionView
]. but when I rotate back to portrait, the layout gets re-centered perfectly.
for some reason it seems like the willTransition
function does not get triggered when rotation is to landscape.
on some little research I done, it seems that it's related to Size classes!! Size classes
don’t cover the difference between iPad Portrait and Landscape: they both have Regular Width and Regular Height, thus the willTransition func does not get called.
What's the simple short work-around for this problem?
Upvotes: 1
Views: 931
Reputation: 462
Try using viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) instead.
It is called when the size of the view managed by the view controller changes, even if the size class doesn't change.
If your layout depends on the transition being completed you can perform the updates after the transition is done:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: nil) { _ in
// perform your updates
}
}
Upvotes: 3
Reputation: 2405
As fast walk around you can try to register for notification which came with every rotation.
NotificationCenter.default.addObserver(self, selector:
#selector(YOUR_SELECTOR), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
And implementation of your selector
if UIDeviceOrientationIsPortrait(UIDevice.current.orientation) {
print("Portrait")
}
if UIDeviceOrientationIsLandscape(UIDevice.current.orientation) {
print("Landscape")
}
Upvotes: 0