Collectionview cell not aligning with collectionview frame

63 Views Asked by At

I am trying to create a fullscreen collection view cell. The collection view is pinned to the edges of the parent view. But the collectionview cells are not aligning with the collectionview frame which is required. Can somebody help?

View hierarchy

View

private func setupPageCollectionView() {
        
        let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection = .horizontal
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        
        self.view.backgroundColor = .red
    
        pageCollectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        pageCollectionView.register(MyCell.self, forCellWithReuseIdentifier: MyCell.reuseIdentifier)
        pageCollectionView.delegate = self
        pageCollectionView.dataSource = self
        pageCollectionView.decelerationRate = .fast
        pageCollectionView.translatesAutoresizingMaskIntoConstraints = false
        
        pageCollectionView.backgroundColor = .blue
        self.view.addSubview(pageCollectionView)
        NSLayoutConstraint.activate([
            pageCollectionView.topAnchor.constraint(equalTo: self.view.topAnchor),
            pageCollectionView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            pageCollectionView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
            pageCollectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
        ])
    }
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return collectionView.bounds.size
    }
2

There are 2 best solutions below

0
kric On

Check the collectionView's contentInsets, contentInsetAdjustmentBehavior and (most likely) insetsLayoutMarginsFromSafeArea.

0
Francesco Leoni On

Does collectionView.bounds.size return the right size?

Maybe there is some top padding in the cell subclass?

Try to implement insetForSectionAt from UICollectionViewDelegateFlowLayout

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    .zero
}