如何在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 } 

请告诉我该如何实施?

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

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

你可以用它

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

我用你的答案@PGDev,但我把它放在viewWillAppear ,它适用于我。

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