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?
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.
A layout object that organizes items into a grid with optional header and footer views for each section.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With