Created
November 27, 2018 12:41
-
-
Save alouanemed/751e7553f3811e5a4caf470303595a77 to your computer and use it in GitHub Desktop.
UICollectionView spacing margins swift 4
This file contains 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
/ Create flow layout | |
let flow = UICollectionViewFlowLayout() | |
// Define layout constants | |
let itemSpacing: CGFloat = 1 | |
let minimumCellWidth: CGFloat = 120 | |
let collectionViewWidth = collectionView!.bounds.size.width | |
// Calculate other required constants | |
let itemsInOneLine = CGFloat(Int((collectionViewWidth - CGFloat(Int(collectionViewWidth / minimumCellWidth) - 1) * itemSpacing) / minimumCellWidth)) | |
let width = collectionViewWidth - itemSpacing * (itemsInOneLine - 1) | |
let cellWidth = floor(width / itemsInOneLine) | |
let realItemSpacing = itemSpacing + (width / itemsInOneLine - cellWidth) * itemsInOneLine / (itemsInOneLine - 1) | |
// Apply values | |
flow.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) | |
flow.itemSize = CGSize(width: cellWidth, height: cellWidth) | |
flow.minimumInteritemSpacing = realItemSpacing | |
flow.minimumLineSpacing = realItemSpacing | |
// Apply flow layout | |
collectionView?.setCollectionViewLayout(flow, animated: false) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment