UICollectionView Set number of columns

后端 未结 17 1205
执笔经年
执笔经年 2020-11-28 17:28

I just started learning about UICollectionViews. I\'m wondering if anyone knows how to specify the number of columns in a collectionview. The default is set to 3 (iPhone/por

17条回答
  •  一个人的身影
    2020-11-28 18:07

    I made a collection layout.

    To make the separator visible, Set the background color of the collection view to gray. One row per section.

    Useage:

    let layout = GridCollectionViewLayout()
    layout.cellHeight = 50 // if not set, cellHeight = Collection.height/numberOfSections
    layout.cellWidth = 50  // if not set, cellWidth = Collection.width/numberOfItems(inSection)
    collectionView.collectionViewLayout = layout
    

    Layout:

    import UIKit
    
    class GridCollectionViewLayout: UICollectionViewLayout {
    
    
    var cellWidth : CGFloat = 0
    var cellHeight : CGFloat = 0
    var seperator: CGFloat = 1
    
    private var cache = [UICollectionViewLayoutAttributes]()
    
    
    
    override func prepare() {
    
        guard let collectionView = self.collectionView else {
            return
        }
    
        self.cache.removeAll()
    
    
    
            let numberOfSections = collectionView.numberOfSections
    
            if cellHeight <= 0
            {
                cellHeight = (collectionView.bounds.height - seperator*CGFloat(numberOfSections-1))/CGFloat(numberOfSections)
            }
    
            for section in 0.. [UICollectionViewLayoutAttributes]? {
    
        var layoutAttributes = [UICollectionViewLayoutAttributes]()
    
        for attributes in cache {
            if attributes.frame.intersects(rect) {
                layoutAttributes.append(attributes)
            }
        }
        return layoutAttributes
    }
    
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        return cache[indexPath.item]
    }
    }
    

提交回复
热议问题