我试图在特定位置滚动单元格(
.bottom
),并在滚动动画完成后运行一些代码。问题是 scrollToItem
函数不提供完成处理程序,因此唯一的解决方案是使用委托 (scrollViewDidEndScrollingAnimation
)。不过,使用它我有一个问题,如果单元格已经位于该位置.didEndScrollAnim
。永远不会被召唤。
有没有办法找到某个单元格是否已经位于
UICollectionView.ScrollPosition.bottom
?
collectionView.scrollToItem(at: indexPath, at: [.bottom,.centeredHorizontally], animated: true)
我希望能够在单元格位于所需位置时运行部分代码 [
.bottom
],并且如果需要滚动,还可以为滚动设置动画。
是的,您可以使用
scrollViewDidEndDecelerating
函数,当滚动视图停止时,该函数将被调用。
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)
}
// 滚动方式不会影响此功能,因此您可以根据需要指定任何位置
我可以想到一个办法,但是需要反复调用
scrollViewDidScroll
,这确实会降低屏幕的性能。
在功能中
scrollViewDidScroll
:
if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
//reach bottom, here your code
}
我将
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
}
)
使用
UIScrollViewDelegate.scrollViewDidEndScrollingAnimation(UIScrollView)
在调用 UICollectionView.scrollToItem(at:at:animated:)
完成动画时收到通知。
以编程方式启动滚动时,不会调用 UIScrollViewDelegate.scrollViewDidEndDecelerating
。