ios 如何快速滚动到集合视图中的特定索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40786699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 10:50:40  来源:igfitidea点击:

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

iosiphonearraysswiftuicollectionview

提问by TechChain

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.

我们有一个集合视图。我制作了一个水平显示日期的日历,并且我水平滚动日期。现在在屏幕上我只看到 3-4 个日期。现在我想在显示日历屏幕时自动滚动到特定的选定日期。所以我想滚动到的日期尚不可见。

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?

请告诉我如何实施它?

回答by PGDev

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

viewDidLoad您的控制器中,您可以编写用于滚动到集合视图的特定索引路径的代码。

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

回答by Pixel

In Swift 4, this worked for me:

在 Swift 4 中,这对我有用:

override func viewDidLayoutSubviews() {

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

placing it anywhere else just resulted in weird visuals.

将它放在其他任何地方只会产生奇怪的视觉效果。

回答by Tigran Torgomyan

You can use this

你可以用这个

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

回答by Vance Huang

I used your answer @PGDev but I put it in viewWillAppearand it works well for me.

我使用了你的回答@PGDev,但我把它放进去了viewWillAppear,它对我来说效果很好。

self.collectionView?.scrollToItem(at:IndexPath(item: yourIndex, section: yourSection), at: .left, animated: false)

回答by Milan Aghera

In viewDidLoad of your controller, you can write the code

在控制器的 viewDidLoad 中,您可以编写代码

     self.myCollectionView.performBatchUpdates(nil) { (isLoded) in

     if isLoded{
                 self.myCollectionView.scrollToItem(at: self.passedContentOffset, at: [.centeredVertically,.centeredHorizontally], animated: false)
               }
      }