Fit given number of cells in uicollectionview per row

后端 未结 5 1485
生来不讨喜
生来不讨喜 2021-01-31 06:52

I have a collection view and I would like to have let\'s say 4 cells per row. I know that to accomplish this all I need to do is divide collectionview.frame.size.width

5条回答
  •  春和景丽
    2021-01-31 07:02

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

    Declare number of cells you want per row

    let numberOfCellsPerRow: CGFloat = 4
    

    Configure flowLayout to render specified numberOfCellsPerRow

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

提交回复
热议问题