Vadim Fainshtein
Vadim Fainshtein

Reputation: 143

Recognizing UIScrollView movement by pixel

I need to change UIScrollView subviews according to their place on the screen, so that they will get smaller while moving up and bigger while moving down.

Is there any way to know the contentOffset with the change of every pixel? I catch the scrollViewDidScroll: method, but whenever the movement is fast there might be some 200pxls change between two calls.

Any ideas?

Upvotes: 4

Views: 523

Answers (1)

sergio
sergio

Reputation: 69027

You have basically two approaches:

  1. subclass UIScrollView and override touchesBegan/Moved/Ended;

  2. add you own UIPanGestureRecognizer to your current UIScrollView.

  3. set a timer, and each time it fires, update your view reading _scrollview.contentOffset.x;

In the first case, you would do for the touch handling methods:

- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {

UITouch* touch = [touches anyObject];
   _initialLocation = [touch locationInView:self.view];
   _initialTime = touch.timestamp;

   <more processing here>

  //-- this will make the touch be processed as if your own logics were not there
  [super touchesBegan:touches withEvent:event];
}

I am pretty sure you need to do that for touchesMoved; don't know if you also need to so something specific when the gesture starts or ends; in that case also override touchesMoved: and touchesEnded:. Also think about touchesCancelled:.

In the second case, you would do something like:

//-- add somewhere the gesture recognizer to the scroll view
UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panView:)];
panRecognizer.delegate = self;
[scrollView addGestureRecognizer:panRecognizer];

//-- define this delegate method inside the same class to make both your gesture
//-- recognizer and UIScrollView's own work together
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
   return TRUE;
}

The third case is pretty trivial to be implemented. Not sure if it will give better results that the other two.

Upvotes: 3

Related Questions