-1

So i have a collectionViewController that I am trying to implement a grid layout in. I know that the sizeForItemAt controls the size but no matter how many times I play with it I just can't get it to be a three by three grid and it's really confusing me. Any help is greatly appreciated. I only added the sizeForItemAt method to save everyone some time.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = (view.frame.width - 2)/3
    return CGSize(width: width, height: width)
}

This is what my VC currently looks like

enter image description here

1 Answers1

2

Conform to UICollectionViewDelegateFlowLayout (docs here)

eg:

class YourClassName: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {
// ...
}

Note, from the docs:

The flow layout object expects the collection view’s delegate object to adopt this protocol. Therefore, implement this protocol on object assigned to your collection view’s delegate property.

So in your viewDidLoad set:

collectionView.delegate = self

and implement the below to calc the cell size:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    // Number of cells
    let collectionViewWidth = collectionView.bounds.width/3.0 
    let collectionViewHeight = collectionViewWidth

    return CGSize(width: collectionViewWidth, height: collectionViewHeight)
}
JaredH
  • 2,110
  • 1
  • 24
  • 38