Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save makthrow/067ec222b81d6a1e2419 to your computer and use it in GitHub Desktop.
Save makthrow/067ec222b81d6a1e2419 to your computer and use it in GitHub Desktop.
set fixed number of cells per row in UICollectionViewController
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.
shareedit
answered Mar 6 at 12:35
sgib
13
*/
@jamesgathu
Copy link

Take note of implementing UICollectionViewDelegateFlowLayout

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment