How to scroll to a particluar index in collection

2019-01-18 23:39发布

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?

3条回答
迷人小祖宗
2楼-- · 2019-01-19 00:15

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)
查看更多
\"骚年 ilove
3楼-- · 2019-01-19 00:20

You can use this

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

查看更多
叛逆
4楼-- · 2019-01-19 00:34

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)
查看更多
登录 后发表回答