Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView is scrolling when selecting a cell

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.

like image 545
Miguelme Avatar asked Dec 04 '15 05:12

Miguelme


4 Answers

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: [])

like image 116
xaphod Avatar answered Nov 18 '22 19:11

xaphod


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.

like image 11
CodeSmith Avatar answered Nov 18 '22 20:11

CodeSmith


In Swift 5 you can do

let indexPath = IndexPath(item: 10, section: 0)

self.collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .init(rawValue: 0))

in viewDidAppear or viewDidLayoutSubviews

like image 4
Radu Ursache Avatar answered Nov 18 '22 19:11

Radu Ursache


You can try this:

collectionView.selectItem(at: newIdexPath, animated: true, scrollPosition: UICollectionViewScrollPosition(rawValue: 0))
like image 3
zhangbangjun Avatar answered Nov 18 '22 19:11

zhangbangjun