我在我的应用中使用UIScrollView
,并使用scrollviewDidScroll
方法移动其他不在滚动视图中的视图。仅当用户实际使用手指移动滚动视图而不是触摸事件结束时才会出现此行为。
目前我正在使用scrollview的dragging
属性来获取此行为,但它有一个问题:当用户在滚动视图上滑动并在停止减速之前再次触摸它时,dragging
虽然用户正用手指拖动滚动视图,但属性不正确。
答案 0 :(得分:29)
UIScrollView
具有panGestureRecogniser
属性,用于跟踪滚动视图中的平移手势。您可以在state
中跟踪平移手势的scrollViewDidScroll
,以准确了解平移的状态。
Swift 4.0
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.isEqual(yourScrollView) {
switch scrollView.panGestureRecognizer.state {
case .began:
// User began dragging
print("began")
case .changed:
// User is currently dragging the scroll view
print("changed")
case .possible:
// The scroll view scrolling but the user is no longer touching the scrollview (table is decelerating)
print("possible")
default:
break
}
}
}
<强>目标C 强>
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if ([scrollView isEqual:yourScrollView]) {
switch (scrollView.panGestureRecognizer.state) {
case UIGestureRecognizerStateBegan:
// User began dragging
break;
case UIGestureRecognizerStateChanged:
// User is currently dragging the scroll view
break;
case UIGestureRecognizerStatePossible:
// The scroll view scrolling but the user is no longer touching the scrollview (table is decelerating)
break;
default:
break;
}
}
}
答案 1 :(得分:4)
IMO更好的答案是使用UIScrollViewDelegate
,有以下通知:
// called on start of dragging (may require some time and or distance to move)
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView;
// called on finger up if the user dragged. velocity is in points/millisecond. targetContentOffset may be changed to adjust where the scroll view comes to rest
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset NS_AVAILABLE_IOS(5_0);
// called on finger up if the user dragged. decelerate is true if it will continue moving afterwards
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate;
答案 2 :(得分:0)
var lastVelocityYSign = 0
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let currentVelocityY = scrollView.panGestureRecognizer.velocity(in: scrollView.superview).y
let currentVelocityYSign = Int(currentVelocityY).signum()
if currentVelocityYSign != lastVelocityYSign &&
currentVelocityYSign != 0 {
lastVelocityYSign = currentVelocityYSign
}
if lastVelocityYSign < 0 {
print("SCROLLING DOWN")
} else if lastVelocityYSign > 0 {
print("SCOLLING UP")
}
}
来自Mos6y的答案 https://medium.com/@Mos6yCanSwift/swift-ios-determine-scroll-direction-d48a2327a004