Reputation: 629
I'm having trouble when i try to select an item inside a UICollectionView
since when I click on it it scrolls a little bit.
I know didSelectItemAtIndexPath
is being called but I want to prevent the scrolling when selecting. I only want the collection view to scroll when the user is scrolling through but if the user is just tapping the cell it shouldn't move. Only should be selected.
I hope you can help me since I don't know how to prevent this problem.
Any help will be really appreciated.
Upvotes: 37
Views: 12281
Reputation: 1529
In Swift 5 you can do
let indexPath = IndexPath(item: 10, section: 0)
self.collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .none)
in viewDidAppear
or viewDidLayoutSubviews
Upvotes: 5
Reputation: 345
In my case, I solved the issue by defining a custom UICollectionViewFlowLayout.
private var flowLayout: UICollectionViewFlowLayout {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
flowLayout.scrollDirection = UICollectionView.ScrollDirection.horizontal
flowLayout.minimumInteritemSpacing = 15
return flowLayout
}
and assigning it to the collectionView
collectionView.collectionViewLayout = flowLayout
Upvotes: 1
Reputation: 1236
swift 5
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}
Upvotes: -3
Reputation: 6804
If you are selecting the cell programmatically with collectionview.selectItem(at: indexpath, animated: true, scrollPosition: .top)
-- and since you didn't share any of your code with us, let's assume that's correct...
... then like me you might not have realized that you can use an empty set like this: collectionview.selectItem(at: indexpath, animated: true, scrollPosition: [])
Upvotes: 107
Reputation: 41
You can try this:
collectionView.selectItem(at: newIdexPath, animated: true, scrollPosition: UICollectionViewScrollPosition(rawValue: 0))
Upvotes: 3
Reputation: 1691
This can happen if you have paging enabled and the CollectionView is manually scrolled to a position that doesn't align with the expected page boundaries. When you select the cell, it adjusts to put the CollectionView at the correct page boundaries.
Upvotes: 12