How do I set collection view's cell size via the auto layout
I don't believe you can set the size by only using the Storyboard because you can't set constraints to recurring items like collection view cells that are created on the fly at runtime.
You can easily compute the size from the information you are given. In collectionView(_:layout:sizeForItemAt:)
you can access the bounds of the collectionView
to compute the desired size of your cell:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// Compute the dimension of a cell for an NxN layout with space S between
// cells. Take the collection view's width, subtract (N-1)*S points for
// the spaces between the cells, and then divide by N to find the final
// dimension for the cell's width and height.
let cellsAcross: CGFloat = 3
let spaceBetweenCells: CGFloat = 1
let dim = (collectionView.bounds.width - (cellsAcross - 1) * spaceBetweenCells) / cellsAcross
return CGSize(width: dim, height: dim)
}
Make sure your class adopts the protocol UICollectionViewDelegateFlowLayout
.
This then works for iPhones and iPads of all sizes.
Great answer by vacawama but I had 2 issues. I wanted the spacing that I defined in storyboard to automatically be used.
And secondly, I could not get this function to invoke and no one mentioned how? In order to invoke the collectionView's sizeForItemAt you need to extend UICollectionViewDelegateFlowLayout instead of extending UICollectionViewDelegate. I hope this saves someone else some time.
extension MyViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellsAcross: CGFloat = 3
var widthRemainingForCellContent = collectionView.bounds.width
if let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout {
let borderSize: CGFloat = flowLayout.sectionInset.left + flowLayout.sectionInset.right
widthRemainingForCellContent -= borderSize + ((cellsAcross - 1) * flowLayout.minimumInteritemSpacing)
}
let cellWidth = widthRemainingForCellContent / cellsAcross
return CGSize(width: cellWidth, height: cellWidth)
}
}
I set it up using CollectionView's delegate methods. This will give you a 2xN setup but you can easily make it a 3xN instead. Here's a screenshot and you can refer to my project on GitHub...
https://github.com/WadeSellers/GoInstaPro