Home > OS >  How do I add left and right inset to UICollectionView contentInset?
How do I add left and right inset to UICollectionView contentInset?

Time:02-11

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?

CodePudding user response:

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

CodePudding user response:

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)
}
  • Related