一个控制器中有多个UICollectionView

Civ*_*rix 7 ios uicollectionview

我有一个视图设置有两个UICollectionViews.这些视图中的每一个都有一个支持不同大小的数组.collection1由array1支持,collection2由array2支持.问题是,从numberOfItemsInSection为collection1返回的任何数字都应用于两个集合视图.

例如,如果array1的大小为4,array2的大小为5,则两个集合都将显示4个元素.如果array1的大小为5而array2的大小为4,那么当我一直滚动collection2时,它会调用cellForItemAtIndexPath,itemIndex为5,这样我就得到了一个N​​SRangeException.

如何让每个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;
}
Run Code Online (Sandbox Code Playgroud)

我已经包含了一个git repo,其中包含一个说明问题的项目.

git@github.com:civatrix/MultipleCollectionViews.git

Civ*_*rix 20

问题是我为每个集合使用相同的布局对象.回想起来有意义,但你必须确保为每个collectionView创建不同的布局.

  • 如何为每个CollectionView使用不同的布局?我有一个自定义布局,并没有让我使用它 (2认同)

小智 5

使用ContainerViews可能会更容易,并且每个UICollectionView都有两个单独的UICollectionView控制器

  • 好建议。这样既可以使代码更清晰,也可以使其更具模块化,因此您可以在不同的地方重用单个集合视图控制器。 (2认同)