Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 541
Flying_Banana Avatar asked Mar 14 '14 03:03

Flying_Banana


People also ask

Does UIView animate need weak self?

You don't need to use [weak self] in static function UIView. animate() You need to use weak when retain cycle is possible and animations block is not retained by self.

Does UIView animate run on the main thread?

The contents of your block are performed on the main thread regardless of where you call [UIView animateWithDuration:animations:] . It's best to let the OS run your animations; the animation thread does not block the main thread -- only the animation block itself.

Is UIView animate asynchronous?

UIView. animate runs on the main thread and is asynchronous.


1 Answers

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.

like image 75
JJC Avatar answered Sep 24 '22 20:09

JJC