Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIScrollView determine scroll direction on scrollViewDidEndDragging when paging

Does anyone know how to determine which direction a scroll view will move when the user lifts their finger, i.e. when scrollViewDidEndDragging gets called?

Specifically, when the scroll view is set to paging.

Most of the time, I can just track and check the contentOffset in scrollViewDidScroll, however, there are special cases where the user flicks the screen quickly. In some cases a LEFT-RIGHT-LEFT move will scroll to the next page, and in others, the same pattern will remain on the same page.

I'm guessing it has something to do the with acceleration (difference between the last few points) of the touch.

(I'm on iOS4.3 on an iPad)

like image 330
Rob Avatar asked Oct 19 '11 23:10

Rob


2 Answers

You don't use timer, which is very expensive operation. Lock the direction of your scrollView first to move only up/down and left/right [I guess that's what you want]. And then use following code to determine...

CGPoint start, end;

- (void)scrollViewWillBeginDragging:(UIScrollView *)sender {
    start = self.scrollView.contentOffset;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)sender willDecelerate:(BOOL)decelerate {
    end = self.scrollView.contentOffset;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)sender {    
    NSLog(@"%d %d",(int)start.x,(int)start.y);
    NSLog(@"%d %d",(int)end.x,(int)end.y);
}
like image 97
Saurin Avatar answered Oct 02 '22 23:10

Saurin


Here is my solution works fine for me hope it helps

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

   CGFloat pageWidth = scrollView.frame.size.width;

   //Old Solution
   //Switch the indicator when more than 30% of the previous/next page is visible
   //You can vary the percentage
   //int page = floor((scrollView.contentOffset.x - pageWidth * 0.3) / pageWidth) + 1;


   //New Solution
    _pageControl.currentPage = (int)scrollView.contentOffset.x / (int)pageWidth;
}

I quit the old solution as the new one seems more slick

like image 43
Dani.Rangelov Avatar answered Oct 03 '22 00:10

Dani.Rangelov