Search code examples
iosswiftuicollectionviewuikituicollectionviewcell

UICollectionview not scroll to item by selectItem function IOS


I can't scroll to the Item with this function of collectionView

collectionView.selectItem(at: IndexPath(row: 10 , section: 0), animated: true, scrollPosition: UICollectionViewScrollPosition.centeredHorizontally) 

This CollectionView is Horizontal


Solution

  • You are currently just selecting collection view item at indexPath, this will not scroll to item. You need to scroll at position of selected item. Add following method to scroll:

    collectionView.selectItem(at: IndexPath(row: 10 , section: 0), animated: true, scrollPosition: UICollectionViewScrollPosition.centeredHorizontally)
    collectionView.scrollToItem(at: IndexPath(row: 10 , section: 0), at: .centeredHorizontally, animated: true)