简体   繁体   中英

iOS collectionView: how to scroll a cell to the top of the screen

I am wondering if there is a way to scroll a certain UICollectionViewCell to the top of the view? I tried the collectionView.scrollToItemAtIndexPath() method, but instead of scrolling the cell to the top of the view, it scroll the cell to the center of the view.

You may use below code:

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
}

However, if you want to force the scrolling, then try this.

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    [collectionView setContentOffset:CGPointMake(cell.center.x - collectionView.frame.size.width * 0.5, cell.frame.origin.y) animated:YES];
}

You can also implement the UIScrollViewDelegate method scrollViewShouldScrollToTop: and return YES if the passed in scroll view is equal to the one that you want to scroll to the top:

-(BOOL) scrollViewShouldScrollToTop:(UIScrollView*) scrollView 
{
    if (scrollView == self.myTableView)
       {
          return YES;
       }
    else 
       {
          return NO;
       }
}

if you don't have more than one scroll view/table view/collection view on screen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM