How to center a UICollectionView when it is tapped?

前端 未结 4 839
说谎
说谎 2021-02-01 08:25

I have a UICollectionView and it has quite a lot of UICollectionViewCells on it. I want to scroll the cell to the centre of the UICollectionView<

4条回答
  •  灰色年华
    2021-02-01 08:43

    Setting contentInsets should give some extra space around first and last cells:

    CGFloat collectionViewHeight = CGRectGetHeight(collectionView.bounds);
    [collectionView
      setContentInset:
       UIEdgeInsetsMake(collectionViewHeight/2, 0, collectionViewHeight/2, 0) ];
      // nb, those are top-left-bottom-right
    

    After you should call:

    [collectionView scrollToItemAtIndexPath:selectedItemPath
        atScrollPosition:UICollectionViewScrollPositionCenteredVertically
        animated:YES];
    

    It's important to pass correct scroll position: UICollectionViewScrollPositionCenteredVertically

    This should center tapped item properly.

    EDIT

    It's really strange, but after setting UIEdgeInsets to collection view method scrollToItemAtIndexPath does not works properly, so i make some modification:

    - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
        CGFloat collectionViewHeight = CGRectGetHeight(self.collectionView.frame);
        [collectionView setContentInset:UIEdgeInsetsMake(collectionViewHeight / 2, 0, collectionViewHeight / 2, 0)];
    
        UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
        CGPoint offset = CGPointMake(0,  cell.center.y - collectionViewHeight / 2);
        [collectionView setContentOffset:offset animated:YES];
    }
    

    it works fine for me.

提交回复
热议问题