Search code examples
objective-ciosanimationcore-animation

iOS Touch, Gestures, Animation


I am exploring iOS4.3 SDK & wanted to implement a particular animation effect. But have no idea how to do it. It goes like this - I have a square box on the screen & upon user putting his finger on the box & dragging his finger the box should follow him. It's easy till here. I was able to implement it like so -

-(void)touchesEnded:(NSSet *)touches 
          withEvent:(UIEvent *)event
{
    UITouch *touch   = [touches anyObject];
    CGPoint location = [touch locationInView:self.view];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:2];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    CGAffineTransform scaleTrans  = CGAffineTransformMakeScale(scaleFactor, scaleFactor);
    CGAffineTransform rotateTrans = CGAffineTransformMakeRotation(angle * M_PI / 180);
    boxView.transform = CGAffineTransformConcat(scaleTrans, rotateTrans);
    angle             = (angle == 180 ? 360 : 180);
    scaleFactor       = (scaleFactor == 2 ? 1 : 2);
    boxView.center    = location;
    [UIView commitAnimations];
}

But as the user lifts his finger, I want the box to carry on with the motion (as if with momentum). It's like the same rubber band scrolling effect apple implements; even when u leave scrolling, the screen scrolls & slowly comes to a stop. How do I implement this?


Solution

  • Why don't you consider using UIPanGestureRecognizer. You can use the translationInView: to move the box as moves the finger across. And when the gesture's state is UIGestureRecognizerStateEnded, you could use velocityInView: to get the desired follow up effect.