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?
In swift:
You can do it also in scrollViewDidScroll.
Codes explains itself I guess. CGFloat difference1 and difference2 declared in same class private interface. Good if contentSize stays same.
Alternatively, it is possible to observe key path "contentOffset". This is useful when it's not possible for you to set/change the delegate of the scroll view.
After adding the observer, you could now:
Do remember to remove the observer when needed. e.g. you could add the observer in viewWillAppear and remove it in viewWillDisappear
In that case, on iOS 5 and above, use the
UIScrollViewDelegate
to determine the direction of the user's pan gesture:Use this delegate method of scrollview.
If y co-ordinate of velocity is +ve scroll view scrolls downwards and if it is -ve scrollview scrolls upwards. Similarly left and right scroll can be detected using x co-ordinate.
Using
scrollViewDidScroll:
is a good way to find the current direction.If you want to know the direction after the user has finished scrolling, use the following: