UICollectionView scroll to item not working with horizontal direction

For iOS 14

Apparently there is a new bug in UICollectionView that is causing scrollToItem to not work when paging is enabled. The work around is to disable paging before calling scrollToItem, then re-enabling it afterwards:

collectionView.isPagingEnabled = false
collectionView.scrollToItem(
    at: IndexPath(item: value, section: 0),
    at: .centeredHorizontally,
    animated: true
)
collectionView.isPagingEnabled = true

Source: https://developer.apple.com/forums/thread/663156


For this part:

collectionView.scrollToItem(at: i, at: .top, animated: true)

When the scroll direction is horizontal you need to use at: left, at: right or at: centeredHorizontally. at: top is for vertical direction.


I had trouble implementing this in a flow layout with entered paging per item. The .centeredHorizontally just wouldn't work for me so i use scroll to rect and Check there is data before scrolling:

    if self.collectionView?.dataSource?.collectionView(self.collectionView!, cellForItemAt: IndexPath(row: 0, section: 0)) != nil {
        let rect = self.collectionView.layoutAttributesForItem(at: IndexPath(item: data[index], section: 0))?.frame
        self.collectionView.scrollRectToVisible(rect!, animated: false)
    }