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
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:
two cell items
four cell items