【发布时间】:2013-12-27 17:39:46
【问题描述】:
我想在 UIScrollview 上实现“下拉刷新”类型的效果。在检测到滚动视图的“顶部”反弹时,视图应该刷新一些组件。 如何检测 UIScrollview 的“顶部反弹”?我尝试了委托“scrollViewWillBeginDragging”,但没有成功。
【问题讨论】:
标签: ios uiscrollview delegates
我想在 UIScrollview 上实现“下拉刷新”类型的效果。在检测到滚动视图的“顶部”反弹时,视图应该刷新一些组件。 如何检测 UIScrollview 的“顶部反弹”?我尝试了委托“scrollViewWillBeginDragging”,但没有成功。
【问题讨论】:
标签: ios uiscrollview delegates
实现scrollViewDidScroll:,查看scrollView.contentOffset.y的值——下拉的时候是负数,弹回来的时候会回到0(或接近0)。根据您要满足的刷新条件,您可以在该值变为特定负值时设置一个标志,然后在它回到接近 0 时进行刷新。像这样:
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (scrollView.contentOffset.y < -50) _metNegativePullDown = YES;
if (fabs(scrollView.contentOffset.y) < 1 && _metNegativePullDown) {
//do your refresh here
_metNegativePullDown = NO;
}
}
【讨论】:
为了记录,我使用这个类别在 Swift 4 上检测到两次反弹:
extension UIScrollView {
var isBouncing: Bool {
var isBouncing = false
if contentOffset.y >= (contentSize.height - bounds.size.height) {
// Bottom bounce
isBouncing = true
} else if contentOffset.y < contentInset.top {
// Top bounce
isBouncing = true
}
return isBouncing
}
}
需要考虑的事项
【讨论】:
当您向下滚动时,大多数答案都会错误地处理这种情况。这里主要是使用adjustedContentInset.bottom,其中包括safeAreaInset 和contentInset。然后它在有和没有缺口的 iPhone 上都能正常工作。
extension UIScrollView {
var isBottomBouncing: Bool {
contentOffset.y > max(0.0, contentSize.height - bounds.height + adjustedContentInset.bottom)
}
}
这是一个非常精确的计算,因此如果您在scrollViewDidScroll 中依赖它,您可能还需要应用一些阈值,因为scrollViewDidScroll 可能无法捕捉到isBottomBouncing 更改为false 的时刻。
【讨论】: