UICollectionView Set number of columns

后端 未结 17 1201
执笔经年
执笔经年 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:09

    Here is the working code for Swift 3, to have a two-columns layout :

    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {
    
        let nbCol = 2
    
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        let totalSpace = flowLayout.sectionInset.left
            + flowLayout.sectionInset.right
            + (flowLayout.minimumInteritemSpacing * CGFloat(nbCol - 1))
        let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(nbCol))
        return CGSize(width: size, height: size)
    }
    

    Feel free to change "nbCol" to your desired number of columns.

提交回复
热议问题