UICollectionView - Scrolling to first cell

后端 未结 8 1569
一生所求
一生所求 2021-02-12 18:00

I\'m making use of UICollectionView and I need to scroll to first cell after click in a button.

The button is located in a (big) header section in my collection view...

相关标签:
8条回答
  • 2021-02-12 18:26

    The following solution works fine for me:

    UIView.animate(withDuration: 0.5, animations: {
         self.collectionView?.contentOffset.x = 0
    })
    

    It scrolls to the first item and the contentInset can be seen as well.

    0 讨论(0)
  • 2021-02-12 18:29

    I found to work reliably on all devices and correctly handle iPhone X-style safe areas.

    let top = CGPoint(x: collectionView.contentOffset.x,
                      y: collectionView.adjustedContentInset.top)
    collectionView.setContentOffset(top, animated: false)
    

    (This scrolls vertically to the top but you could easily make it scroll to the top-left if you wanted.)

    0 讨论(0)
提交回复
热议问题