Several UICollectionViews Scroll Horizontally like

2019-08-05 00:53发布

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条回答
贪生不怕死
2楼-- · 2019-08-05 01:47

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.

查看更多
登录 后发表回答