如何使用组合布局在 UICollectionView 内均匀间隔固定大小的单元格?

Mar*_*aka 0 math uikit uicollectionview swift uicollectionviewcompositionallayout

我有一个使用组合布局创建的集合视图。每个项目都有固定的宽度和高度,并且该部分占据表格的整个宽度(表格本身占据屏幕的整个宽度)。我正在尝试创建一种算法来计算内容和部分插入,使每个项目之间的间距相等,并且屏幕边框之间的间距也相等。换句话说,所有东西之间的空间应该是相同的。

以下是计算内容和章节插入的方法:

// width is 414
private func getContentInsets(width: CGFloat) -> NSDirectionalEdgeInsets {
    let totalItemsInRow = Int(width / 120) // 3
    let totalCellWidth = 120 * totalItemsInRow // 360
    let remainingSpace = width - CGFloat(totalCellWidth) // 54
    let marginPerItem = remainingSpace / CGFloat(totalItemsInRow) // 18
    return NSDirectionalEdgeInsets(top: 8, leading: marginPerItem / 2, bottom: 8, trailing: marginPerItem / 2)
}

// width is 414    
private func getSectionContentInsets(width: CGFloat) -> NSDirectionalEdgeInsets {
    let totalItemsInRow = CGFloat(Int(width / 120)) // 3
    return NSDirectionalEdgeInsets(top: 0,
                                   leading: getContentInsets(width: width).leading * totalItemsInRow, // 9 * 3 = 27
                                   bottom: 0,
                                   trailing: getContentInsets(width: width).trailing * totalItemsInRow) // 9 * 3 = 27
}
Run Code Online (Sandbox Code Playgroud)

使用这些方法,我能够在项目之间拥有相等的空间。但它们与屏幕边框的空间不同,如下图所示:

内容和部分插入的结果,它将项目置于屏幕中间居中,但在边框中添加了更大的空间

那么,我如何更改这些算法以实现项目之间以及屏幕边框之间的相等间距(所有内容都应具有相同的间距)。

Mar*_*aka 5

感谢 Felipe 只分配主值的想法,我能够修复算法。不幸的是,这个公式并没有解决问题,因为集合视图的尾部边框仍然留有一个小空间。我还注意到,用于在集合视图的单元格之间添加空间的正确属性是edgeSpacing,而不是contentInsets

所以我删除了插入部分,然后edgeSpacing像这样分配:

private func getEdgeSpacing(width: CGFloat) -> NSCollectionLayoutEdgeSpacing {
    let totalItemsInRow = Int(width / 120)
    let totalCellWidth = 120 * totalItemsInRow
    let remainingSpace = width - CGFloat(totalCellWidth)
    let totalMargins = totalItemsInRow
    let marginPerItem = remainingSpace / CGFloat(totalMargins)
    return NSCollectionLayoutEdgeSpacing(leading: NSCollectionLayoutSpacing.fixed(marginPerItem / 2),
                                         top: nil,
                                         trailing: NSCollectionLayoutSpacing.fixed(marginPerItem / 2),
                                         bottom: nil)
}
Run Code Online (Sandbox Code Playgroud)

唯一的固定值是120,它是每个单元格的固定宽度。