Created
April 22, 2020 01:35
-
-
Save SunXiaoShan/01697f82d75714fc4b788f6e160141f9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class ColumnFlowLayout: UICollectionViewFlowLayout { | |
| let cellsPerRow: Int | |
| init(cellsPerRow: Int, minimumInteritemSpacing: CGFloat = 0, minimumLineSpacing: CGFloat = 0, sectionInset: UIEdgeInsets = .zero) { | |
| self.cellsPerRow = cellsPerRow | |
| super.init() | |
| self.minimumInteritemSpacing = minimumInteritemSpacing | |
| self.minimumLineSpacing = minimumLineSpacing | |
| self.sectionInset = sectionInset | |
| } | |
| required init?(coder aDecoder: NSCoder) { | |
| fatalError("init(coder:) has not been implemented") | |
| } | |
| override func prepare() { | |
| super.prepare() | |
| guard let collectionView = collectionView else { return } | |
| let marginsAndInsets = sectionInset.left + sectionInset.right + collectionView.safeAreaInsets.left + collectionView.safeAreaInsets.right + minimumInteritemSpacing * CGFloat(cellsPerRow - 1) | |
| let itemWidth = ((collectionView.bounds.size.width - marginsAndInsets) / CGFloat(cellsPerRow)).rounded(.down) | |
| itemSize = CGSize(width: itemWidth, height: itemWidth) | |
| } | |
| override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext { | |
| let context = super.invalidationContext(forBoundsChange: newBounds) as! UICollectionViewFlowLayoutInvalidationContext | |
| context.invalidateFlowLayoutDelegateMetrics = newBounds.size != collectionView?.bounds.size | |
| return context | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment