I am using a UIScrollView
in my app, and use the scrollviewDidScroll
method to move some other views that are not inside the scrollview. This behavior should only occur when the user is actually moving the scrollview with a finger and not when the touch event ends.
Currently I am using the dragging
property of the scrollview to get this behavior, but it has a problem: when the user swipes over the scrollview and touches it again before it stopped decelerating, the dragging
property is not true although the user is dragging the scrollview with a finger.
The UIScrollView
has a panGestureRecogniser
property, which tracks the pan gestures in the scroll view. You can track the state
of the pan gesture in the scrollViewDidScroll
to know exactly what state the panning is in.
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
}
}
}
Objective-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;
}
}
}
IMO better answer is use of UIScrollViewDelegate
, there are following notifications:
// 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With