Tuesday, 30 September 2014

Add UIPanGestureRecognizer to View

Adding PanGestureRecognizer to your view its very easy.

Here i have added PanGestureRecognizer to ImageView. so i can move my imageview in my view.

Add following code to any method to add PanGestureRecognizer to your view. i added this to ViewWillAppear.


-(void)viewWillAppear:(BOOL)animated
{
         UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];

          [panRecognizer setMinimumNumberOfTouches:1];

          [panRecognizer setMaximumNumberOfTouches:1];

          [ViewMain addGestureRecognizer:panRecognizer];

          [panRecognizer release];
}
- (Void)handlePan:(UIPanGestureRecognizer *)recognizer
    {
   
         CGPoint translation = [recognizer translationInView:self.view];
         recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                         recognizer.view.center.y + translation.y);
         [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
     
         if (recognizer.state == UIGestureRecognizerStateEnded) {
       
             CGPoint velocity = [recognizer velocityInView:self.view];
             CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
            CGFloat slideMult = magnitude / 200;
            NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);
       
            float slideFactor = 0.1 * slideMult; // Increase for more of a slide
            CGPoint finalPoint = CGPointMake(recognizer.view.center.x + (velocity.x * slideFactor),
                                         recognizer.view.center.y + (velocity.y * slideFactor));
        finalPoint.x = MIN(MAX(finalPoint.x, 0), self.view.bounds.size.width);
        finalPoint.y = MIN(MAX(finalPoint.y, 0), self.view.bounds.size.height);
       
        [UIView animateWithDuration:slideFactor*2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
            recognizer.view.center = finalPoint;
        } completion:nil];
       
    }
   
    }


Thanks & Regards
Angel AppTech

No comments:

Post a Comment

Note: only a member of this blog may post a comment.