Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 904
alpaca Avatar asked Dec 15 '22 02:12

alpaca


2 Answers

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.

like image 50
gwinyai Avatar answered Feb 20 '23 17:02

gwinyai


UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout

Adding all 3 delegates are important. Esp. UIDelegateFlowLayout.

like image 22
king-of-everything Avatar answered Feb 20 '23 16:02

king-of-everything