Skip to content

Instantly share code, notes, and snippets.

@alouanemed
Created November 27, 2018 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alouanemed/751e7553f3811e5a4caf470303595a77 to your computer and use it in GitHub Desktop.
Save alouanemed/751e7553f3811e5a4caf470303595a77 to your computer and use it in GitHub Desktop.
UICollectionView spacing margins swift 4
/ 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