Ios – Fit given number of cells in uicollectionview per row

iosobjective cuicollectionviewuicollectionviewcell

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 by 4. This is easy. However, what I can not figure out, is how to take into consideration the insets at the side of the collection view and the spacing between the cells. I have 10 pixel insets on the left and right of the collection view, as well as there is a 10 pixel spacing between the cells. How can I calculate the required cell width taking these 10 px insets into account?

Best Answer

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)
}