简体   繁体   中英

How can I change the speed (or duration) of a UIView block animation, while its animating?

I have an image view that I am very slowly animating across the screen, on repeat, using a block animation as follows:

[UIView animateWithDuration:100.0f
                      delay:0.0f
                    options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionRepeat
                 animations:^(void) {
                     pattern.frame = CGRectMake(0-(pattern.frame.size.width/2), 0, pattern.frame.size.width, pattern.frame.size.height);
                 }
                 completion:NULL];

Basically the image is twice the width of the screen, and when it repeats it looks like it continuously loops around.

This all works fine, but what I would like to do is speed up or slow down the scrolling based on a rotation touch gesture. I have a gesture recognizer set up etc, but can I alter the current animation to speed up?

If not, can I cancel the current running one and replace it with another animation of a shorter/longer duration?

BTW, I have tried using exactly the same animation block in my gesture recogniser, something like:

-(void)rotatedSpinner:(UIRotationGestureRecognizer *)gestureRecognizer{
    CGFloat rotation = gestureRecognizer.rotation;

    [UIView animateWithDuration:100-(rotation*10)
             delay:0.0f
             options:UIViewAnimationOptionBeginFromCurrentState
             animations:^(void) {
                 pattern.frame = CGRectMake(0-(pattern.frame.size.width/2), 0, pattern.frame.size.width, pattern.frame.size.height);
             }
             completion:NULL];
}

..but it doesn't seem to do anything at all? Any help appreciated.

If you want to have a slowly scrolling view that the user can also scroll with his fingers, I recommend using a UIScrollView. You could use an NSTimer to continuously update the scroll view's content offset. When the user starts scrolling you simply deactivate this timer, let him scroll however he wants. Once he let's go and the scroll view stops decelerating (your delegate will be notified) you can start moving it yourself again.

If you want the rotation gesture to speed up or slow down the animation like turning a dial, try this:

Set the speed property on the view's layer.

Most UIView animations end up adding a CAAnimation to the view's layer object, so that should work. Something like this:

pattern.layer.speed = .5 //Slow the animation down to half-speed

A value of 2 will stop the animation completely. A value of 2 will make it run at double speed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM