2017-06-12 90 views
1

迅速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函数..也许这些事情变得复杂,如果使用二维数组。而这个问题与其他部分的立场有关。

它可能只有一维数组?我的想法是正确的?

+0

你如何决定哪些项目适合哪个部分?每节只有三个项目吗? – overactor

+0

@ oractor是的。 – Byoth

回答

0

如果您在每节还有三个项目,你可以简单地计算出你有多少部分,每个部分项目有:

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 
} 
+0

很好的答案。谢谢! – Byoth

+0

@Byoth,如果它解决了您的问题,请不要忘记注册并/或标记为已接受。 – overactor

+0

我只知道投票..但它需要15点声望。所以我觉得我什么都做不了。感谢您的评论,我现在知道'Mark'。我不会忘记它。 – Byoth