迅速UICollectionView部分分离
问题描述:
// My data to use
let items: [Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ...]
/*
// UICollectionView result I want
<Section [Item1, Item2, Item3]>
<Other Section A>
<Section [Item4, Item5, Item6]>
<Other Section B>
<Section [Item7, Item8, Item9]>
<Other Section A>
<Section [Item10, Item11, Item12]>
<Other Section B>
*/
如果我的数据是象下面一个二维数组,我可以看到结果更容易。
let items: [[Any]] = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ...]
但我想我应该只使用一维数组。
因为我的项目会经常增加/删除。并需要API通信..并需要LoadMore函数..也许这些事情变得复杂,如果使用二维数组。而这个问题与其他部分的立场有关。
它可能只有一维数组?我的想法是正确的?
答
如果您在每节还有三个项目,你可以简单地计算出你有多少部分,每个部分项目有:
func numberOfSections(in collectionView: UICollectionView) -> Int {
return items.count/3 + 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return min(3, items.count - 3 * section)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let item = items[indexPath.section * 3 + item]
// do something with item
}
你如何决定哪些项目适合哪个部分?每节只有三个项目吗? – overactor
@ oractor是的。 – Byoth