Search code examples
iphoneobjective-ciosuigesturerecognizeruiswipegesturerecognizer

ios UISwipeGestureRecognizer calculate offset


I'm adding swipe gesture recognizer to my application

- (void)createGestureRecognizers
{

    //adding swipe up gesture
    UISwipeGestureRecognizer *swipeUpGesture= [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeUpGesture:)];
    [swipeUpGesture setDirection:UISwipeGestureRecognizerDirectionUp];
    [self.view addGestureRecognizer:swipeUpGesture];
    [swipeUpGesture release];
}

And the method to handle swipe events:

-(IBAction)handleSwipeUpGesture:(UISwipeGestureRecognizer *)sender
{
    NSLog(@"handleSwipeUpGesture: called");
}

How can I calculate offset here? to move the view?


Solution

  • The UIGestureRecognizer abstract superclass for UISwipeGestureRecognizer has the foollowing methods

    - (CGPoint)locationInView:(UIView *)view
    - (CGPoint)locationOfTouch:(NSUInteger)touchIndex inView:(UIView *)view
    

    Which allow you to know the position of the gesture in the view, but this is a discrete gesture recognizer (which will fire at a given "translation" or "offset" whatever you want to call it, which you cannot control). It sounds like you are looking for continuous control, for this you want a UIPanGestureRecognizer which has the following methods (which do the translation calculations for you)

    - (CGPoint)translationInView:(UIView *)view
    - (void)setTranslation:(CGPoint)translation inView:(UIView *)view
    - (CGPoint)velocityInView:(UIView *)view
    

    You will then get quick fire callbacks while the gesture is continuously unfolding.