Fit given number of cells in uicollectionview per row

后端 未结 5 1466
生来不讨喜
生来不讨喜 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:05

    Swift 4+

    UICollectionViewDataSource method

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

提交回复
热议问题