首页 > 解决方案 > 无论我做什么,CollectionView Cells 都不会在视图中居中

问题描述

我无法将我的 CollectionView 单元格集中在 Collection View 上。这就是我现在在 Stackoverflow 上找到的(但尝试了一些其他不起作用的解决方案):

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

    let totalCellWidth = cellWidth * CGFloat(posts.count)
    let totalSpacingWidth = CGFloat(cellSpacing * (posts.count - 1))
    let collectionViewWidth = collectionView.frame.width

    let leftInset = (collectionViewWidth - (totalCellWidth + totalSpacingWidth)) / 2
    let rightInset = leftInset

    return UIEdgeInsets(top: 0, left: leftInset, bottom: 0, right: rightInset)

}

我尝试编写自己的解决方案,但没有任何效果。

cellWidth、cellHeight 和 cellSpacing 是固定数字。这就是我得到的: 在此处输入图像描述

标签: swiftuicollectionview

解决方案


推荐阅读