Expanding on noob's answer:
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let totalSpace = flowLayout.sectionInset.left
+ flowLayout.sectionInset.right
+ (flowLayout.minimumInteritemSpacing * CGFloat(numberOfItemsPerRow - 1))
let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(numberOfItemsPerRow))
return CGSize(width: size, height: size)
}
This allows for any spacing between the cells. It assumes an Int
member variable called numberOfItemsPerRow
and also that all the cells are square and the same size. As noted in jhilgert00's answer we must also react to orientation changes, but now by using viewWillTransitionToSize
as willRotateToInterfaceOrientation
is depreciated.