ioscocoa-touchcaanimation

Making an animation to expand and shrink an UIView


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.


Solution

  • 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.