Your answer is one click away!

Balázs Vincze February 2016
### 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?

faarwa February 2016

```
(collectionView.frame.size.width-50)/4
```

To account for the space, you can subtract it from the collection view frame width (subtracting `5*10`

).

leokwanbt14 February 2016
#### Post Status

#### Search

To better explain the math, faarwa's example is only for 4 cells. Assuming 1 row, there are 5 blocks of spacing for 4 cell items (stick out 4 fingers and count the spaces from far end of pinky to far end of index finger).

There will always be n + 1 spaces for the n cells you have in one row. Faarwa assumes each space is 10 so he multiplied 5 cells by 10 to get 50. You need to figure out how much space you have left to work with after paddingâ€” so if assuming your screen width is 200, you must subtract the two values to get the remaining width, or "(collectionView.frame.size.width-50)".

Continuing with the 200 width assumption and 4 cell items, you must divide your difference (150) by 4 to get the width each cell should be for equal spacing.

Experiment and go through some trial and error, but here are the 2 methods I used to get a collection view of exercise sets from an array of set objects.

```
// UICollectionViewDataSource method
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let numberOfSets = CGFloat(self.currentExSets.count)
let width = (collectionView.frame.size.width - (numberOfSets * view.frame.size.width / 15))/numberOfSets
let height = collectionView.frame.size.height / 2
return CGSizeMake(width, height);
}
// UICollectionViewDelegateFlowLayout method
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAtIndex section: Int) -> UIEdgeInsets {
let cellWidthPadding = collectionView.frame.size.width / 30
let cellHeightPadding = collectionView.frame.size.height / 4
return UIEdgeInsets(top: cellHeightPadding,left: cellWidthPadding,
bottom: cellHeightPadding,right: cellWidthPadding)
```

}

SCREENSHOT:

Asked in February 2016

Viewed 1,111 times

Voted 13

Answered 2 times

Viewed 1,111 times

Voted 13

Answered 2 times