How to scroll to a particluar index in collection view in swift
Solution 1
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)
Solution 2
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.
Solution 3
You can use this
self.collectionView.scrollToItem(at:IndexPath(item: index, section: 0), at: .right, animated: false)
Solution 4
I used your answer @PGDev but I put it in viewWillAppear
and it works well for me.
self.collectionView?.scrollToItem(at:IndexPath(item: yourIndex, section: yourSection), at: .left, animated: false)
Solution 5
In viewDidLoad of your controller, you can write the code
self.myCollectionView.performBatchUpdates(nil) { (isLoded) in
if isLoded{
self.myCollectionView.scrollToItem(at: self.passedContentOffset, at: [.centeredVertically,.centeredHorizontally], animated: false)
}
}
TechChain
I have 4+ of experience of overall experience.Currently working on Hyperledger Fabric blockchain framework. I have strong knowledge of Objective c, Swift.I have developed lot of apps from chat app, finance apps,location & map based apps.
Updated on July 05, 2022Comments
-
TechChain almost 2 years
We have a collection view. I have made a calendar which shows dates horizontally & I scroll dates horizontally. Now on screen I see only 3-4 dates. Now I want to auto scroll to a particular selected date when calendar screen I shown.So the date I want to scroll to is not visible yet.
For that I got the indexpath for particular cell. Now I am trying to scroll it to particular indexpath.
func scrollCollectionView(indexpath:IndexPath) { // collectionView.scrollToItem(at: indexpath, at: .left, animated: true) //collectionView.selectItem(at: indexpath, animated: true, scrollPosition: .left) collectionView.scrollToItem(at: indexpath, at: .centeredHorizontally, animated: true) _ = collectionView.dequeueReusableCell(withReuseIdentifier: "DayCell", for: indexpath) as? DayCell }
Please tell how can I implement it?