如何在swift中滚动到集合视图中的特定元素索引

Tec*_*ain 13 arrays iphone ios uicollectionview swift

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

为此,我获得了特定单元格的索引路径.现在我试图将其滚动到特定的索引路径.

  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

  }
Run Code Online (Sandbox Code Playgroud)

请告诉我该如何实现它?

PGD*_*Dev 23

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

self.collectionView.scrollToItem(at:IndexPath(item: indexNumber, section: sectionNumber), at: .right, animated: false)
Run Code Online (Sandbox Code Playgroud)


小智 7

你可以用它

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


小智 6

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

self.collectionView?.scrollToItem(at:IndexPath(item: yourIndex, section: yourSection), at: .left, animated: false)
Run Code Online (Sandbox Code Playgroud)


Pix*_*xel 6

在SWift 4中,这对我有用:

override func viewDidLayoutSubviews() {

    collectionView.scrollToItem(at:IndexPath(item: 5, section: 0), at: .right, animated: false)
}
Run Code Online (Sandbox Code Playgroud)

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