Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView scroll to item not working with horizontal direction

I have a UICollectionView within a UIViewController with paging enabled. For some strange reason collectionView.scrollToItem works when the direction of the collectionview is vertical but doesn't when direction is horizontal. Is this there something I'm doing wrong or is this supposed to happen?

  //Test scrollToItem
  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let i = IndexPath(item: 3, section: 0)
    collectionView.reloadData()
    collectionView.scrollToItem(at: i, at: .top, animated: true)
    print("Selected")
  }
like image 491
kye Avatar asked Jan 26 '17 23:01

kye


2 Answers

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

like image 55
LunaCodeGirl Avatar answered Nov 13 '22 23:11

LunaCodeGirl


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.

like image 45
kl.woon Avatar answered Nov 13 '22 23:11

kl.woon