2012-10-12 13 views
6

我有一個視圖設置了兩個UICollectionViews。這些視圖中的每一個都有一個支持不同大小的數組。 collection1由array1支持,而collection2由array2支持。問題是,從numberOfItemsInSection中爲collection1返回的數字正在應用於這兩個集合視圖。在一個控制器中的多個UICollectionView

例如,如果是ARRAY1大小4和數組2是大小5,兩個集合將顯示4個元素。如果array1的大小是5而array2的大小是4,那麼當我滾動collection2的所有方式時,它會調用cellForItemAtIndexPath,其collectionIndex爲5,我得到一個NSRangeException。

我怎樣才能讓每一個使用的CollectionView它自己的尺寸?

- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section; 
{ 
    if(view == self.colleciton1){ 
     return self.array1.count; 
    } else if (view == self.collection2){ 
     return self.array2.count; 
    } 

    return 0; 
} 

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath; 
{ 
    if(cv == self.collection1){ 
     CharacterCell *cell = [cv dequeueReusableCellWithReuseIdentifier:FIRST_CELL_IDENTIFIER forIndexPath:indexPath]; 
     cell.label.text = self.array1[indexPath.item]; 
     return cell; 
    } else if (cv == self.collection2){ 
     EpisodeCell *cell = [cv dequeueReusableCellWithReuseIdentifier:SECOND_CELL_IDENTIFIER forIndexPath:indexPath]; 
     cell.label.text = self.array2[indexPath.item]; 
     return cell; 
    } 

    return nil; 
} 

我已經包括一個項目說明問題的git回購。

[email protected].com:civatrix/MultipleCollectionViews.git

回答

19

的問題是,我是用每個集合相同的佈局對象。回想起來,這是有道理的,但你必須確保你爲每個collectionView創建不同的佈局。

+0

這是正確的。我有同樣的問題。 –

+0

謝謝!這也解決了我的問題! – ordinaryman09

+0

向上和謝謝!也解決了我的! – z33

1

你有什麼應該工作。是self.colleciton1和self.collection2 IBOutlets?如果是這樣,你可以仔細檢查他們是否正確連接?

+0

一切都正確迷上了,我看到一些在每個集合視圖的元素。 – Civatrix

3

也許會更容易使用ContainerViews,有兩個獨立的UICollectionView控制器每個UICollectionView

+1

好的建議。這將使代碼更清晰並使其更加模塊化,以便您可以在不同的地方重新使用各個集合視圖控制器。 –

相關問題