iOS Swift 4 Coding

How to fill UICollectionViewCell equally over UICollectionView in Xcode with Swift 4?

2 views October 24, 2018 October 24, 2018 bicobro 0

When you want to have the UICollectionViewCells of a UICollectionView sized equally, you have to add a function to handle size differences. Do the following:

Add the following protocols to the CollectionView ViewController:

  • UICollectionViewDataSource
  • UICollectionViewDelegate
  • UICollectionViewDelegateFlowLayout

See this example:

class MyCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    ...
}

Add the following method to the CollectionView ViewController to control the size of the cells:

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

To show 2 items per row, you can write the following code:

func collectionView(_ collectionView: UICollectionView, layout _: UICollectionViewLayout, sizeForItemAt _: IndexPath) -> CGSize {
    let padding: CGFloat = 30
    let collectionViewSize = collectionView.frame.size.width - padding
        
    return CGSize(width: collectionViewSize / 2, height: 69)
}

Was this helpful?