Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

ios - Multiple UICollectionView in one controller

I have a view set up with two UICollectionViews. Each of these views has an array backing it with different sizes. collection1 is backed by array1, and collection2 is backed by array2. The problem is, what ever number is returned for collection1 from numberOfItemsInSection is being applied to both collection views.

For instance, if array1 is size 4 and array2 is size 5, both collections will show 4 elements. If array1 is size 5 and array2 is size 4, when I scroll collection2 all the way it calls cellForItemAtIndexPath with an itemIndex of 5 for collection2 and I get an NSRangeException.

How can I make each collectionView use it's own size?

- (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;
}

I've included a git repo with a project illustrating the problem.

[email protected]:civatrix/MultipleCollectionViews.git

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem was that I was using the same layout object for each collection. In retrospect that makes sense, but you have to make sure you create different layouts for each collectionView.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...