UICollectionView align logic missing in horizontal paging scrollview

前端 未结 16 1204
天命终不由人
天命终不由人 2020-12-07 06:49

I\'ve got a UICollectionView, which works ok, until I start scrolling. Here some pics first: \"enter

16条回答
  •  难免孤独
    2020-12-07 07:31

    My answer is based on answer https://stackoverflow.com/a/27242179/440168 but is more simple.

    enter image description here

    You should place UIScrollView above UICollectionView and give them equal sizes:

    @property (nonatomic, weak) IBOutlet UICollectionView *collectionView;
    @property (nonatomic, weak) IBOutlet UIScrollView *scrollView;
    

    Then configure contentInset of collection view, for example:

    CGFloat inset = self.view.bounds.size.width*2/9;
    self.collectionView.contentInset = UIEdgeInsetsMake(0, inset, 0, inset);
    

    And contentSize of scroll view:

    self.scrollView.contentSize = CGSizeMake(self.placesCollectionView.bounds.size.width*[self.collectionView numberOfItemsInSection:0],0);
    

    Do not forget to set delegate of scroll view:

    self.scrollView.delegate = self;
    

    And implement main magic:

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView
    {
        if (scrollView == self.scrollView) {
            CGFloat inset = self.view.bounds.size.width*2/9;
            CGFloat scale = (self.placesCollectionView.bounds.size.width-2*inset)/scrollView.bounds.size.width;
            self.collectionView.contentOffset = CGPointMake(scrollView.contentOffset.x*scale - inset, 0);
        }
    }
    

提交回复
热议问题