我正在尝试将具有动态大小的项目的项目集中在 Collection View 上。我想将这些项目居中,在某些情况下可以每行一个,有时两个。我找到了一种基于设置部分插入来居中项目的解决方案,但这要求所有项目的大小相同:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
let totalCellWidth = CellWidth * CellCount
let totalSpacingWidth = CellSpacing * (CellCount - 1)
let leftInset = (collectionViewWidth - CGFloat(totalCellWidth + totalSpacingWidth)) / 2
let rightInset = leftInset
return UIEdgeInsetsMake(0, leftInset, 0, rightInset)
}
这是我的 Collection View 的图像,其中包含“对齐”的项目,它们之间有动态间距:
我的目标是更改每行的插图,使项目居中并且它们之间的间距始终相同。
知道我如何才能实现这一目标吗?
最佳答案
正如评论中所解释的,您必须为您的 collectionView 使用自定义布局。首先,您可以引用以下链接。
- https://octodev.net/custom-collectionviewlayout/
- https://www.raywenderlich.com/164608/uicollectionview-custom-layout-tutorial-pinterest-2
- https://www.netguru.co/codestories/practical-introduction-to-custom-uicollectionview-layouts
P.S:由于在 stackoverflow 上不建议仅共享链接,因此我将尽快更新答案并概述使用自定义布局所需的基本步骤。
关于ios - 将 UICollectionView 每行的插入设置为具有动态宽度的中心项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51428367/