Several UICollectionViews Scroll Horizontally like

2019-08-05 01:23发布

问题:

I am trying to do a view that contains several collectionViews. Swiping left or right would scroll to another collectionView.

I have added a scrollView as a first step with paging enabled. I also set the content size to the number of pages.

int nb_of_items = 10;

    // Scroll view
    for (int i=0; i< nb_of_items ; i++) {
        CGRect frame = CGRectMake(_scrollView.frame.size.width * i,
                                  0,
                                  _scrollView.frame.size.width,
                                  _scrollView.frame.size.height);

                _collectionView.frame = frame;
                [_scrollView addSubview:_collectionView];
    }

    _scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width * nb_of_items, _scrollView.frame.size.height);

    _scrollView.delegate = self;

The collectionView is defined in my storyboard and has the datasource and delegate set to self. I am only getting the collection on the first page. On the other pages I get nothing.

I also tried to refresh the collection when the scrollView decelerates

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self updateCollection];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate) {
        [self updateCollection];
    }
}

-(void)updateCollection{

    NSLog(@"Updating Collection");
    [_collectionView reloadData];

}

Any ideas how I could fix that ?

回答1:

Remember that a collection view is a scroll view, so you already have the ability to scroll. You already know that scroll views can constrain the scrolling to full pages only. So, you can set the collection view to use pages and then the user can scroll between each part of your collection content.

All you need to do is to ensure that the layout scrolls in the correct direction (horizontal instead of vertical) and that each page has the appropriate contents. You probably want to create your own layout for that, though it could work with a flow layout so long as you set the item size appropriately.