使用动作将 CollectionView 滚动到下一个单元格

Using an action to scroll CollectionView to the next cell

我有一个水平的 collectionview,每次我点击按钮都会添加一个新的单元格。一旦每次点击按钮时单元格不再可见,我将尝试将集合视图滚动到下一个单元格。

我现在的代码不能正常工作

代码:

@IBAction func random(_ sender: Any) {

    resultsCollection.reloadData()

    let collectionBounds = resultsCollection.bounds
    let contentOffset = CGFloat(floor(resultsCollection.contentOffset.x - collectionBounds.size.width))
    self.moveToFrame(contentOffset: contentOffset)

}

func moveToFrame(contentOffset : CGFloat) {

    let frame: CGRect = CGRect(x : contentOffset ,y : resultsCollection.contentOffset.y ,width : resultsCollection.frame.width,height : resultsCollection.frame.height)
        resultsCollection.scrollRectToVisible(frame, animated: true)
}

我该如何解决这个问题,以便在我点击按钮时它可以正确滚动?

使用下面的代码来实现你的需求。对于动画,你只需要在 scrollToRow 函数的 animated 中传递值 true/false 即可。 希望对您有所帮助!

在没有动画的情况下滚动到顶部

func scrollToTopWithoutAnimation() {
     DispatchQueue.main.async {
         if self.dataArray.count > 0 {
             let indexPath = IndexPath(row: 0, section: 0)
             collectionView.scrollToItem(at: indexPath, at: .top, animated: false)
         }
     }
}

用动画滚动到顶部

func scrollToTopWithAnimation() {
     DispatchQueue.main.async {
         if self.dataArray.count > 0 {
             let indexPath = IndexPath(row: 0, section: 0)
             collectionView.scrollToItem(at: indexPath, at: .top, animated: true)

         }
     }
}

Set IndexPath row as per your needs

重新加载数据后,调用此行。

let lastItem = resultsCollection(resultsCollection, numberOfItemsInSection: 0) - 1
let indexPath = IndexPath(row: lastItem, section: 0)

resultsCollection.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)