Skip to content

Instantly share code, notes, and snippets.

@sebjvidal
Created April 19, 2026 21:32
Show Gist options
  • Select an option

  • Save sebjvidal/9e47261f6097cfb5f372c3b696f859ab to your computer and use it in GitHub Desktop.

Select an option

Save sebjvidal/9e47261f6097cfb5f372c3b696f859ab to your computer and use it in GitHub Desktop.
Collection View Layout Margins Demo
private func setupCollectionView() {
let layout = UICollectionViewCompositionalLayout { [unowned self] section, environment in
let spacing: CGFloat = 8
let numberOfColumns: CGFloat = 5
let numberOfSpacers: CGFloat = numberOfColumns - 1
let contentWidth = collectionView.layoutMarginsGuide.layoutFrame.width
let itemWidth = (contentWidth - numberOfSpacers * spacing) / numberOfColumns
let layoutItemSize = NSCollectionLayoutSize(widthDimension: .absolute(itemWidth), heightDimension: .fractionalHeight(1))
let layoutItem = NSCollectionLayoutItem(layoutSize: layoutItemSize)
let layoutGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(itemWidth))
let layoutGroup = NSCollectionLayoutGroup.horizontal(layoutSize: layoutGroupSize, subitems: [layoutItem])
layoutGroup.interItemSpacing = .fixed(spacing)
let headerSupplementaryItemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(100))
let headerSupplementaryItem = NSCollectionLayoutBoundarySupplementaryItem(layoutSize: headerSupplementaryItemSize, elementKind: UICollectionView.elementKindSectionHeader, alignment: .top)
let layoutSection = NSCollectionLayoutSection(group: layoutGroup)
layoutSection.interGroupSpacing = spacing
layoutSection.contentInsetsReference = .layoutMargins
layoutSection.boundarySupplementaryItems = [headerSupplementaryItem]
return layoutSection
}
collectionView = UICollectionView(collectionViewLayout: layout)
collectionView.delegate = self
collectionView.preservesSuperviewLayoutMargins = true
collectionView.backgroundColor = .systemGroupedBackground
collectionView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: view.topAnchor),
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment