How to scroll a list of objects as a collection in swift

We have a collection view. I made a calendar that shows dates horizontally, and I scroll the dates horizontally. Now on the screen I see only 3-4 dates. Now I want it to automatically scroll to the specific date selected when the calendar screen was shown. So the date I want to scroll through is not yet displayed.

For this, I got the index path for a specific cell. Now I'm trying to scroll it to a specific index path.

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 } 

Tell me how can I implement it?

+12
source share
4 answers

In the viewDidLoad your controller, you can write code to scroll through a specific collection pointer path.

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

You can use this

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

+6
source

I used your @PGDev answer, 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) 
+3
source

In SWift 4, this worked for me:

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

placing it elsewhere led to strange visual effects.

0
source

Source: https://habr.com/ru/post/1260278/


All Articles