【问题标题】:How to detect if scrollToItem will scroll如何检测scrollToItem是否会滚动
【发布时间】:2019-05-24 10:13:17
【问题描述】:

我正在尝试在特定位置 (.bottom) 滚动单元格,并在滚动动画完成后运行一些代码。问题是scrollToItem 函数没有提供完成处理程序,因此唯一的解决方案是使用委托 (scrollViewDidEndScrollingAnimation)。使用它我有一个问题,如果单元格已经在那个位置.didEndScrollAnim。永远不会被调用。

有没有办法找到一个单元格是否已经在UICollectionView.ScrollPosition.bottom

collectionView.scrollToItem(at: indexPath, at: [.bottom,.centeredHorizontally], animated: true)

我希望能够在单元格位于所需位置 [.bottom] 时运行部分代码,并在需要滚动时为滚动设置动画。

【问题讨论】:

  • 最简单的方法是在滚动视图停止时调用scrollViewDidEndDecelerating

标签: ios swift uicollectionview uiscrollview uicollectionviewcell


【解决方案1】:

是的,您可以使用scrollViewDidEndDecelerating func,当滚动视图停止(停止)时,此 func 将调用。

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let secondItemIndex = IndexPath(item: 1, section: 0)
    categoryCollectionView.selectItem(at: secondItemIndex, animated: true, scrollPosition: .centeredHorizontally)

}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

    let secondItemIndex = IndexPath(item: 2, section: 0)
    categoryCollectionView.selectItem(at: secondItemIndex, animated: true, scrollPosition: .centeredHorizontally)

}

// 滚动方式不影响此功能,因此您可以根据需要指定任何位置

【讨论】:

  • 当视图滚动或动画结束时不会调用该函数。collectionView.selectItem(at: indexPath, animated: true, scrollPosition: [.bottom, .centeredHorizontally]) 将滚动到该项目而不调用该函数,如果该索引路径中没有停止。
【解决方案2】:

我可以想到一个办法,但是涉及到反复调用scrollViewDidScroll,确实会降低屏幕的性能。

在函数scrollViewDidScroll

if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
        //reach bottom, here your code
    }

【讨论】:

    【解决方案3】:

    我将animated 参数设置为false 并使用UIView.animate() 来检测动画完成。

    UIView.animate(withDuration: 0.2, animations: { [weak self] in
            self?.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
        }, completion: { [weak self] _ in
            // do something after scroll animation completed
        }
    )
    

    【讨论】:

    • 对我来说似乎不起作用,我需要检测何时完成滚动到该项目并突出显示它
    猜你喜欢
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多