Search code examples
iosuiviewcatransform3danimatewithdurationuilongpressgesturerecogni

Continuous animation in iOS?


In my case I have a view with content. I want to scroll this content on UILongPressGestureRecognizer events:

  • if the touch position y is enough near the up view border then scroll up;
  • if the touch position y is enough near the bottom view border then scroll down.

I can't simply use scrollView so I used CATransform3D structs and animateWithDuration:... methods. The problem is I don't know how long should I scroll (the duration of the scroll animation). The second problem is animation should be called when the touch position (of long press gesture) is changed - it seems easy but may have influence on the final solution.

How to solve such issue?


Solution

  • I am not sure if I understood your question correctly, here I share a method that listens to longPressRecognizer and animates a view as long as user presses onto that view. As user stops pressing, view animates back to its default state. You can check if user gesture satisfies your position conditions by adding position check statements to if/else if's. Hope that helps.

    - (void)longPressed:(UILongPressGestureRecognizer *)recognizer {
        UIView *longPressView = self.longPressView;
        if (recognizer.state == UIGestureRecognizerStateBegan) {
            [UIView animateWithDuration:longPressDuration
                                  delay:0.f
                                options:UIViewAnimationOptionCurveLinear|UIViewAnimationOptionBeginFromCurrentState
                             animations:^{
                                 //do stuff
                             }
                             completion:^(BOOL finished) {
                                 if (finished) {
                                     //long press exceeded time limit: do stuff
                                 }
                             }];
        }
        else if (recognizer.state == UIGestureRecognizerStateEnded) {
            [UIView animateWithDuration:longPressDuration/2.0
                                  delay:0.f
                                options:UIViewAnimationOptionCurveEaseInOut|UIViewAnimationOptionBeginFromCurrentState
                             animations:^{
                                 //do stuff
                             }
                             completion:nil];
        }
    }