How to scroll to a particluar index in collection view in swift How to scroll to a particluar index in collection view in swift arrays arrays

How to scroll to a particluar index in collection view in swift


In viewDidLoad of your controller, you can write the code for scrolling to a particular index path of collection view.

self.collectionView.scrollToItem(at:IndexPath(item: indexNumber, section: sectionNumber), at: .right, animated: false)


In Swift 4, this worked for me:

override func viewDidLayoutSubviews() {    collectionView.scrollToItem(at:IndexPath(item: 5, section: 0), at: .right, animated: false)}

placing it anywhere else just resulted in weird visuals.

Note - an edit was made to my original post just now which wanted to change viewDidLayoutSubviews() to viewDidAppear(). I rejected the edit because placing the function's code anywhere else (including viewDidAppear) didn't work at the time, and the post has had 10 upvots which means it must have been working for others too. I mention it here in case anyone wants to try viewDidAppear, but I'm pretty sure I would have tried that and wouldn't have written "placing it anywhere else just resulted in weird visuals" otherwise. It could be an XCode update or whatever has since resolved this; too long ago for me to remember the details.


You can use this

self.collectionView.scrollToItem(at:IndexPath(item: index, section: 0), at: .right, animated: false)