UICollectionView spacing margins

后端 未结 15 1008
一向
一向 2020-11-30 16:58

I have a UICollectionView which shows photos. I have created the collectionview using UICollectionViewFlowLayout. It works good but I would like to

15条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 17:39

    Modern Swift, Automatic Layout Calculation

    While this thread already contains a bunch of useful answers, I want to add a modern Swift version, based on William Hu's answer. It also improves two things:

    • The spacing between different lines will now always match the spacing between items in the same line.
    • By setting a minimum width, the code automatically calculates the number of items in a row and applies that style to the flow layout.

    Here's the code:

    // 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 / max(1, 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)
    

提交回复
热议问题