I have a UIScrollView
with only horizontal scrolling allowed, and I would like to know which direction (left, right) the user scrolls. What I did was to subclass the UIScrollView
and override the touchesMoved
method:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesMoved:touches withEvent:event];
UITouch *touch = [touches anyObject];
float now = [touch locationInView:self].x;
float before = [touch previousLocationInView:self].x;
NSLog(@"%f %f", before, now);
if (now > before){
right = NO;
NSLog(@"LEFT");
}
else{
right = YES;
NSLog(@"RIGHT");
}
}
But this method sometimes doesn't get called at all when I move. What do you think?
When paging is turned on,you could use these code.
I checked some of the answer and elaborated on AnswerBot answer by wrapping everything in a drop in UIScrollView category. The "lastContentOffset" is saved inside the uiscrollview instead and then its just a matter of calling :
Source code at https://github.com/tehjord/UIScrollViewScrollingDirection
Swift 4:
For the horizontal scrolling you can simply do :
For vertical scrolling change
.x
with.y
In iOS8 Swift I used this method:
I have a dynamic view which changes locations as the user scrolls so the view can seem like it stayed in the same place on the screen. I am also tracking when user is going up or down.
Here is also an alternative way:
I prefer to do some filtering, based on @memmons's answer
In Objective-C:
When tested in
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
:self.lastContentOffset
changes very fast, the value gap is nearly 0.5f.It is not necessary.
And occasionally, when handled in accurate condition, your orientation maybe get lost. (implementation statements skipped sometimes)
such as :
In Swift 4:
If you work with UIScrollView and UIPageControl, this method will also change the PageControl's page view.
Thanks @Esq 's Swift code.