Device rotation is quite a tricky thing to handle in iOS. Today we'll take a look at how to modify out login component to redraw the layout of our UICollectionView cells when transitioning to landscape/portrait orientations.
In addition, we'll render different images based on which orientation we are in. Finally we will make sure the page is in the right location when the device is rotated
!codebreak
<div class='filename'>ViewController.swift</div>
!codebreak
!syntax-highlight
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
//...
func keyboardShow() {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
let y: CGFloat = UIDevice.current.orientation.isLandscape ? -100 : -50
self.view.frame = CGRect(x: 0, y: y, width: self.view.frame.width, height: self.view.frame.height)
}, completion: nil)
}
//...
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
collectionView.collectionViewLayout.invalidateLayout()
let indexPath = IndexPath(item: pageControl.currentPage, section: 0)
//scroll to indexPath after the rotation is going
DispatchQueue.main.async {
self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
self.collectionView.reloadData()
}
}
}
!codebreak
<div class='filename'>PageCell.swift</div>
!codebreak
!syntax-highlight
class PageCell: UICollectionViewCell {
var page: Page? {
didSet {
guard let page = page else {
return
}
var imageName = page.imageName
if UIDevice.current.orientation.isLandscape {
imageName += "_landscape"
}
imageView.image = UIImage(named: imageName)
//...
}
//...
}