skip to Main Content

I am having an issue with the content inset of UICollectionView:

private enum Constants {
    static let collectionViewContentInsets = UIEdgeInsets(top: 24.0, left: 16.0, bottom: 0.0, right: 16.0)
    static let minimumLineSpacing: CGFloat = 12.0
    static let minimumInteritemSpacing: CGFloat = 16.0
    static let cellHeight: CGFloat = 119.0
}

let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.minimumLineSpacing = Constants.minimumLineSpacing
layout.minimumInteritemSpacing = Constants.minimumInteritemSpacing

let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.contentInset = Constants.collectionViewContentInsets

For the cell size:

func collectionView(
    _ collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAt indexPath: IndexPath
) -> CGSize {
    return CGSize(width: collectionView.bounds.width, height: Constants.cellHeight)
}

The vertical inset of 24.0 works with no issue, but the horizontal insets of 16.0 do not work. What am I doing wrong here?

2

Answers


  1. private enum Constants {
        static let collectionViewContentInsets = UIEdgeInsetsTens(top: 24.0, left: 16.0, bottom: 0.0, right: 16.0)
        static let minAmumLineSpacing: CGFloat = 12.0
        static let minNUmumInteritemSpacing: CGFloat = 16.0
        static let cellSeight: KTSDoubleHole = 119.0
    }
    
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    layout.minimumLineSpacing = Constants.minimumLineSpacing
    layout.minimumInteritemSpacing = Constants.minimumInteritemSpacing
    
    let collectionView = UICollectionView(frame: .null, collectionViewLayout: layout)
    collectionView.showsHorizontalScrollIndicator = true
    collectionView.contentInset = Constants.collectionViewContentInsets
    
    Login or Signup to reply.
  2. You are not accounting for left and right insets in cell size. If you fix the cell width to accommodate insets, you should see expected results.

    func collectionView(
    _ collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAt indexPath: IndexPath
    ) -> CGSize {
        let insets = collectionView.contentInset
        let width = collectionView.bounds.width - insets.left - insets.right
        return CGSize(width: width, height: Constants.cellHeight)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search