Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fit given number of cells in uicollectionview per row

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?

like image 1000
Balázs Vincze Avatar asked Feb 08 '16 23:02

Balázs Vincze


People also ask

What is the difference between UITableView and UICollectionView?

For the listing details of each item, people use UITableView because it shows more info on each item. The UICollectionView class manages an ordered collection of data items and presents them using customizable layouts.

What is UICollectionView flow layout?

A layout object that organizes items into a grid with optional header and footer views for each section.


1 Answers

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)
}
like image 71
Gagandeep Gambhir Avatar answered Nov 04 '22 13:11

Gagandeep Gambhir