alpaca alpaca - 1 year ago 169
Swift Question

UICollectionViewCell not filling the entire screen in Swift 3

enter image description here

I have a UICollectionView with its cells covering the entire screen. My problem here is that there's a small space on the right that's showing a different cell. I want each cell to cover the full width of the screen.

Here's what I've tried:

  1. set min spacing to 0 from Storyboard

  2. set each cell to fit the entire view frame

private func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: view.frame.height)

Is there anything else that I should do to resolve this issue?

Answer Source

The correct Swift 3 implementation should be

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let itemWidth = collectionView.bounds.width
        let itemHeight = collectionView.bounds.height
        return CGSize(width: itemWidth, height: itemHeight)

This will make each collection view cell fill up the entire collection view. It should not be private. Now all you need to do is make sure your collection view stretches across the entire view.

Also make sure to extend your ViewController to include UICollectionViewDelegateFlowLayout for the above method to work and change all section insets to be 0 in Storyboard.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download