Skip to content

Instantly share code, notes, and snippets.

@zwaldowski
Created October 31, 2016 23:14
Show Gist options
  • Save zwaldowski/666297e2a0633835b8a54c095b6a06e0 to your computer and use it in GitHub Desktop.
Save zwaldowski/666297e2a0633835b8a54c095b6a06e0 to your computer and use it in GitHub Desktop.
// This incantation works well for a fullscreen, paging collection view.
// Non-fullscreen works too, with a little finesse.
extension MyCollectionViewController {
private func updateCollectionViewLayout(forBoundingSize size: CGSize) { ... }
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateCollectionViewLayout(forBoundingSize: self.view.bounds.size)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
updateCollectionViewLayout(forBoundingSize: size)
if view.window == nil {
view.frame.size = size
view.layoutIfNeeded()
} else {
let indexPath = self.collectionView?.indexPathsForVisibleItems.last
coordinator.animate(alongsideTransition: { ctx in
self.collectionView?.layoutIfNeeded()
}, completion: { _ in
guard let indexPath = indexPath else { return }
self.collectionView?.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
})
}
}
// MARK: UICollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView, targetContentOffsetForProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
guard let indexPath = collectionView.indexPathsForVisibleItems.last, let layoutAttributes = collectionView.collectionViewLayout.layoutAttributesForItem(at: indexPath) else {
return proposedContentOffset
}
return CGPoint(x: layoutAttributes.center.x - (layoutAttributes.size.width / 2.0) - (flowLayout.minimumLineSpacing / 2.0), y: 0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment