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

sy5wg1nm  于 2023-01-08  发布在  Swift
关注(0)|答案(8)|浏览(434)

我们有一个集合视图。我做了一个日历,它水平显示日期,我水平滚动日期。现在在屏幕上我只看到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

  }

请告诉我如何实现它?

wgmfuz8q

wgmfuz8q1#

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

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

raogr8fs2#

在Swift 4中,这对我很有效:

override func viewDidLayoutSubviews() {

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

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

注意-刚才对我的原始帖子进行了编辑,希望将viewDidLayoutSubviews()更改为viewDidAppear()。我拒绝了编辑,因为将函数的代码放在了其他任何地方(包括viewDidAppear)在那个时候不起作用,而且这个帖子已经有10个upvots,这意味着它一定也在为其他人工作。我在这里提到它,以防有人想尝试viewDidAppear。但我很确定我会尝试一下,否则就不会写“把它放在其他地方只会导致奇怪的视觉效果”。太久了我记不清细节了。

1sbrub3j

1sbrub3j3#

你可以用这个

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

eoxn13cs4#

我用了你的答案@PGDev,但我把它放在viewWillAppear中,它对我很有效。

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

sxpgvts35#

测试了这个

func scrollToIndex(index:Int) {
     let rect = self.collectionView.layoutAttributesForItem(at:IndexPath(row: index, section: 0))?.frame
     self.collectionView.scrollRectToVisible(rect!, animated: true)
 }
e0bqpujr

e0bqpujr6#

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

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

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

olhwl3o27#

我都试过了,但对我来说,只需要多加一行就行了

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

你可以在任何地方调用它。

kiz8lqtg

kiz8lqtg8#

- just add this method to below function.

    override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
            YourcollectionView.scrollToItem(at:IndexPath(item: passedIndex ?? 0, section: 0), at: .centeredVertically, animated: false)
 }

相关问题