2017-06-12 43 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