繁体   English   中英

没有二维数组的快速 UICollectionView 部分分离

[英]swift UICollectionView section separation without Two-Dimensional Array

示例

// 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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM