Question

I'm using a CABasicAnimation instance to animate the scaling of a UIControl upon tap. The functionality should be that the control will scale to 0.9 and then stay there while it is still being pressed, and when the user releases his/her finger, it will enlarge back to its original size.

So far I have created the animation and it works perfectly up until the point where it will animate back to its original size. Instead of creating a separate animation to do the enlarging, I am simply removing the original animation. Is there a way of animation this removal so that it will effectively look like the control is shrinking and enlarging in response to touch?

- (void)shrinkView {
    CABasicAnimation *shrink = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    shrink.toValue = @(0.9);
    shrink.duration = 0.5;
    shrink.delegate = self;
    shrink.removedOnCompletion = NO;
    shrink.fillMode = kCAFillModeForwards;
    [self.layer addAnimation:shrink forKey:@"shrink"];
}

- (void)enlargeView {
    [self.layer removeAnimationForKey:@"shrink"];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self reduceBackgroundOpacity];
    [self shrinkView];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    [self increaseBackgroundOpacity];
    [self enlargeView];
}
Was it helpful?

Solution

You're making this harder than it needs to be. The stuff about removedOnCompletion and removeAnimationForKey: is bogus. Just animate a scale transform when the touch starts and animate back to the identify transform when the touch ends.

(You don't even need to use CABasicAnimation; a simple UIView animation will do - unless you're using autolayout, in which case CABasicAnimation is better.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top