How to animate zoomScale on a UIScrollView
Asked Answered
G

1

6

I need to set zoomScale back to 1 on a UIScrollView, but I need it to be animated. I thought I could use CABasicAnimation for this, but NSValue doesn't seem to have a "valueForFloat" or "valueForNSNumber", so I'm not sure what to use for animation.fromValue and animation.toValue for the CABasicAnimation. Is there a better way to go about this?

EDIT: What do I need to add for this to work?

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"zoomScale"];
        animation.duration = 2.3;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];        
        animation.fromValue = [NSNumber numberWithFloat:myScrollview.zoomScale];
        animation.toValue = [NSNumber numberWithFloat:1.0];

        [myScrollview.layer addAnimation:animation forKey:@"zoomScale"];
Grindle answered 11/6, 2013 at 21:2 Comment(1)
Try to add the animation on the view that is animated not on the scrollView, because I think that the scroll's layer is not changed but the zoomed view's layer is changed.Katharinekatharsis
R
14

You don’t need to resort to CAAnimation for this simple thing, just use -[UIScrollView setZoomScale:animated:] passing YES as the second parameter.

Anyway, if you wanted to do modify some aspect of the animation you may resort using “UIView animations” instead, since zoomScale is not directly a property animatable by CAAnimation.

Have you tried something like the following?

[UIView animateWithDuration:2.0
                      delay:0
                    options:UIViewAnimationOptionBeginFromCurrentState
                 animations:^{ [myScrollView setZoomScale:1.0f animated:NO]; }
                 completion:nil];
Reinhardt answered 11/6, 2013 at 21:6 Comment(2)
I want to set my own animation time though. I don't want the default animation time of setZoomScale:animated:Grindle
The you should use NSNumber instances as values for fromValue and toValue.Reinhardt

© 2022 - 2024 — McMap. All rights reserved.