Search code examples
iosswiftuicollectionviewuicollectionviewcelluicollectionviewlayout

CollectionViewCell margin?


I have a UICollectionView and there are some dequeued custom cells in it. As you can see from the screenshot, there's this odd margin and I cannot figure out where this come from. The brown/orange color is the UICollectionView and the grey color is the UICollectionViewCell.

I'm using a xib file for that cell because I'd need many custom cells.

enter image description here

enter image description here

And the code that generates the UICollectionView has nothing that would cause this margin.

extension DashVC: UICollectionViewDelegate, UICollectionViewDataSource
{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PostImageCell", for: indexPath) as! PostImageCell
        let post = posts[indexPath.row]
        let user = users[indexPath.row]
        cell.post = post
        cell.user = user
        cell.delegate = self
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return posts.count
    }

    func setCollectionViewDelegatesAndRowHeight()
    {
        collectionView.dataSource = self
        collectionView.delegate = self
    }
}

UPDATE:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,   sizeForItemAt indexPath: IndexPath) -> CGSize
{
    let width = Int(UIScreen.main.bounds.width)
    let height = 407
    let size = CGSize(width: width, height: height)
    return size
}

Solution

  • Your UICollectionView width is 375 and UICollectionViewCell width is 320. You are seeing the difference. To make your cells as wide as the screen you can make your controller conform to the UICollectionViewDelegateFlowLayout, and implement the following method:

    - (CGSize)collectionView:(UICollectionView *)collectionView
                      layout:(UICollectionViewLayout *)collectionViewLayout
      sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
        CGRect screenRect = [[UIScreen mainScreen] bounds];
        CGFloat screenWidth = screenRect.size.width;
        cellHeight = 407.0
        CGSize size = CGSizeMake(screenWidth, cellHeight);
    
        return size;
    }