Making an animation to expand and shrink an UIView

Flying_Banana picture Flying_Banana · Mar 14, 2014 · Viewed 25.2k times · Source

I want to create an animation that will resize an UIView and its contents by a factor. Basically, I want to make an animation that first expands the view then shrinks it back to the original size.

What is the best way to do this? I tried CALayer.contentScale but it didn't do anything at all.

Answer

JJC picture JJC · Mar 14, 2014

You can nest some animation blocks together like so:

Objective-C:

[UIView animateWithDuration:1
                 animations:^{
                     yourView.transform = CGAffineTransformMakeScale(1.5, 1.5);
                 }
                 completion:^(BOOL finished) {
                     [UIView animateWithDuration:1
                                      animations:^{
                                          yourView.transform = CGAffineTransformIdentity;
                                          
                                      }];
                 }];

Swift 2:

UIView.animateWithDuration(1, animations: { () -> Void in
    yourView.transform = CGAffineTransformMakeScale(1.5, 1.5)
    }) { (finished: Bool) -> Void in
        UIView.animateWithDuration(1, animations: { () -> Void in
            yourView.transform = CGAffineTransformIdentity
        })}

Swift 3/4/5:

UIView.animate(withDuration: 1, animations: {
    yourView.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
}) { (finished) in
    UIView.animate(withDuration: 1, animations: { 
        yourView.transform = CGAffineTransform.identity
    })
}

and replacing the scale values and durations with your own.