【问题标题】:Using an action to scroll CollectionView to the next cell使用动作将 CollectionView 滚动到下一个单元格
【发布时间】:2019-11-19 18:17:20
【问题描述】:

我有一个水平集合视图,每次点击按钮时都会添加一个新单元格。每次点击按钮时,一旦单元格不再可见,我就会尝试将 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)
}

如何解决此问题,以便在我点击按钮时正确滚动?

【问题讨论】:

  • 你试过了吗? self.collectionView?.scrollToItem(at:IndexPath(item: yourIndex, section: yourSection), at: .left, animated: false)

标签: ios swift uicollectionview uislider


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    使用以下代码来实现您的需求。对于动画,您只需要在 scrollToRow 函数的动画中传递值 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)
    
             }
         }
    }
    

    根据需要设置 IndexPath 行

    【讨论】:

      猜你喜欢
      • 2016-08-03
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多