I did google enough, & I did check posts like these ( Finding the direction of scrolling in a UIScrollView? ) in stackoverflow before posting this. I have a dynamic numb
Building off of @Oscar's answer, you can do things like
scrollView.bounces = actualPosition.y < 0
if you want the scrollView to bounce when you scroll to the bottom but not when you scroll to the top
Swift 3 Solution
1- Add UIScrollViewDelegate
2- Add this code
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
let actualPosition = scrollView.panGestureRecognizer.translation(in: scrollView.superview)
if (actualPosition.y > 0){
// Dragging down
}else{
// Dragging up
}
}
I had no issues determining direction in scrollViewWillBeginDragging
when checking the scroll view's panGestureRecognizer
:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
CGPoint translation = [scrollView.panGestureRecognizer translationInView:scrollView.superview];
if(translation.y > 0)
{
// react to dragging down
} else
{
// react to dragging up
}
}
I found it very useful in canceling out of a scroll at the very first drag move when the user is dragging in a forbidden direction.
There seem to be issues with detecting scroll direction based on the translation of the scrollView's pan recognizer in iOS 7+. This seems to be working pretty seamlessly for my purposes
func scrollViewDidScroll(scrollView: UIScrollView) {
if !scrollDirectionDetermined {
let translation = scrollView.panGestureRecognizer.translationInView(self.view)
if translation.y > 0 {
println("UP")
scrollDirectionDetermined = true
}
else if translation.y < 0 {
println("DOWN")
scrollDirectionDetermined = true
}
}
}
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
scrollDirectionDetermined = false
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
scrollDirectionDetermined = false
}
scrollView.panGestureRecognizer translationInView:scrollView
doesn't report anything useful in scrollViewWillBeginDragging
in iOS 7.
This does:
In the @interface
BOOL scrollDirectionDetermined;
and:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (!scrollDirectionDetermined) {
if ([scrollView.panGestureRecognizer translationInView:scrollView.superview].x > 0) {
//scrolling rightwards
} else {
//scrolling leftwards
}
scrollDirectionDetermined = YES;
}
}
and:
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
scrollDirectionDetermined = NO;
}
For swift 2.0+ & ios 8.0+
func scrollViewWillBeginDecelerating(scrollView: UIScrollView) {
let actualPosition = scrollView.panGestureRecognizer.translationInView(scrollView.superview)
if (actualPosition.y > 0){
// Dragging down
}else{
// Dragging up
}
}