Reset scroll on UICollectionView

前端 未结 9 1188
太阳男子
太阳男子 2021-01-30 05:25

I have a horizontal UICollectionView which works fine and scrolls. When I tap an item I update my data and call reloadData. This works and the new data

相关标签:
9条回答
  • 2021-01-30 05:39

    You want setContentOffset:. It takes a CGPoint as and argument that you can set to what ever you want using CGPointMake, but if you wish to return to the very beginning of the collection, you can simply use CGPointZero.

    [collectionView setContentOffset:CGPointZero animated:YES];
    
    0 讨论(0)
  • 2021-01-30 05:46

    I use this quite often in different parts of my app so I just extended UIScrollView so it can be used on any scroll view and scroll view subclass:

    extension UIScrollView {        
        /// Sets content offset to the top.
        func resetScrollPositionToTop() {
            self.contentOffset = CGPoint(x: -contentInset.left, y: -contentInset.top)
        }
    }
    

    So whenever I need to reset the position:

    self.collectionView.resetScrollPositionToTop()
    
    0 讨论(0)
  • 2021-01-30 05:50

    CGPointZero in my case shifted the content of the collection view because you are not taking in count the content inset. This is what it worked for me:

        CGPoint topOffest = CGPointMake(0,-self.collectionView.contentInset.top);
        [self.collectionView setContentOffset:topOffest animated:YES];
    
    0 讨论(0)
提交回复
热议问题