UICollectionView Set number of columns

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

    Swift 3.0. Works for both horizontal and vertical scroll directions and variable spacing

    Specify number of columns

    let numberOfColumns: CGFloat = 3
    

    Configure flowLayout to render specified numberOfColumns

    if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
        let horizontalSpacing = flowLayout.scrollDirection == .vertical ? flowLayout.minimumInteritemSpacing : flowLayout.minimumLineSpacing
        let cellWidth = (collectionView.frame.width - max(0, numberOfColumns - 1)*horizontalSpacing)/numberOfColumns
        flowLayout.itemSize = CGSize(width: cellWidth, height: cellWidth)
    }
    

提交回复
热议问题