There’s no doubt about it: making animations is one of the most enjoyable aspects of iOS development. A carefully designed and detailed animation effect can give users a refreshing effect and attract their attention, which is very important for an APP.

As the first part of the animation collection, this article originally wanted to explain how to make water drop Animations for QQ drop-down refresh. However, these days I read iOS Animations by Tutorials and gained a deeper understanding of iOS animation development. So I decided to start with UIView Animations. In the future, there will also be animation of Layer, Transitioning and so on. I hope this paper can bring you a different understanding. Here is a demo illustration of the book. Buy books




First put this article demo: click on this PS: this article belongs to the novice to the animation entry article

Start with the login animation

For a long time, I’ve been implementing animations based on the CALayer layer, ignoring the animation interface THAT UIKit provides for us. These interface functions are powerful enough and flexible enough to meet most of the animation requirements of our development.

Before we get into these powerful interfaces, let’s take a look at the first effect: when the user opens the app and logs in, the account and password fields enter from the left side of the screen, followed by the login button.




Interface animation

The most obvious thing that happens in this animation is the position change of the two text boxes. Before the animation starts, the position of the two text boxes should be on the left side of the screen, and the button below is now hidden (set alpha).




Before the animation starts

Therefore, what happens in this animation can be summarized as the following code:

self.userName.center.x += offset; // enter self.password.center. X += offset; // enter self.login.alpha = 1; // Displays the login buttonCopy the code

Now that we know what’s going on with our animation, can we use UIKit’s animation API to make our animation come alive

// Set the initial position of the text box to the left of the screen CGPoint accountCenter = self.username. CGPoint psdCenter = self.password.center; accountCenter.x -= 200; pasCenter.x -= 200; self.userName.center = accountCenter; self.password.center = psdCenter; // Restore center coordinates accountCenter.x += 200; psdCenter.x += 200; [UIView animateWithDuration: 0.5 animations: ^{ self.userName.center = accountCenter; self.password.center = passwordCenter; self.login.alpha = 1; } completion: nil];Copy the code

In UIKit, the system provides class methods on UIView that start with animate to make it easy to animate effects. Each of these class methods provides a block of code called animations that can be executed immediately or after a method is called. In addition, the first parameter in all of these apis is used to set the animation duration.

Run this code in viewDidAppear:, and you’ll see the text field slide from the left and the button gradually appear, but it’s not quite what we want — the three animations aren’t staggered, and it doesn’t look very good. We want the password field to appear some time after the account text field has been swiped, and the button to appear later as well. Therefore, we need to use the following method to achieve this effect:

[UIView animateWithDuration: delay 0.5:0.35 options: UIViewAnimationOptionCurveEaseInOut animations: ^{self.passwordcenter = passwordCenter;} completion: ^(BOOL finished) {[UIView animateWithDuration: 0.2 animations: ^{ self.login.alpha = 1; }]; }];Copy the code

This method looks very familiar, with several more parameters to highly customize our animation:

  • Duration: animation duration
  • Delay: Determines how long the animation should be delayed before execution
  • Options: Used to determine how the animation should be displayed, as explained below
  • Animations: Code that transforms into animated representations
  • Completion: The block of code to be executed after the animation is completed

In the code above, the password entry box starts to come out from the left after a 0.35 second delay, and after an animation that lasts 0.5 seconds, the button begins to fade, and the animation is complete.

Properties that can be animated

You are now ready to make simple animations, but remember that not all changes to properties in the animations code block should be animated — no matter how much you change a view’s tag, or its delegate. Therefore, animatable properties must cause the view to be rerendered. These animating properties can be roughly divided into three categories: coordinate dimensions, view display, and shape changes

Coordinate size class

  • Bounds: Modifying this property combinescenterAttribute recalculationframe. It is recommended to change the size through this property
  • Frame: Changing this property usually causes the view to move as well as deform, and then resetcenterwithboundsattribute
  • Center: Set the rear view to move to a new location, which will be combined after modificationboundsrecalculateframe




    Size change

View display class

  • BackgroundColor: Changing this property produces a gradient of color, which is essentially what the system does by constantly modifying tintColor
  • Alpha: Changing this property will fade in and out
  • Hidden: Modify this property to create a page-turning hidden effect




    Modify transparency

Morphologic class

  • Transform: This property allows you to animate things like rotation, deformation, movement, flip, etc. It’s more powerful because it’s done using matrix arithmetic




Animation parameters

The animation method we used above has an important parameter, Options, which allows you to highly customize the animation effect. Here is a set of values for this parameter type. You can animate your own by combining different parameters:

  • Repeating

    UIViewAnimationOptionRepeat loop execution UIViewAnimationOptionAutoreverse / / / / animation animation in after the execution will reverse direction to perform againCopy the code

    We go to these two parameters into the above password box appears in the animation, and see what effect (different parameters using the | operator incoming together)

    [UIView animateWithDuration: 0.5 delay: 0.35 options: UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat animations: ^{self.passwordcenter = passwordCenter;} completion: ^(BOOL finished) {[UIView animateWithDuration: 0.2 animations: ^{ self.login.alpha = 1; }]; }];Copy the code



    Repetitive animation

    You can see that the password box loops in and out of the screen, and the login button doesn’t fade. Thus can know UIViewAnimationOptionRepeat parameters is not only let the animation loop, and it also contributed to the completion callback can never be performed.

  • Easing we all know that a good animation should be more consistent with our cognitive rules. For example, nothing can suddenly start to move and stop, like a car starting and stopping has a process of acceleration and deceleration.




    The acceleration and deceleration of the car

    To make the animation more consistent with our cognition, the system also provides parameters for similar effects to be used:

    UIViewAnimationOptionCurveEaseInOut / / speed before slowing down, The default UIViewAnimationOptionCurveEaseIn / / from slow to fast UIViewAnimationOptionCurveEaseOut / / from fast to slow UIViewAnimationOptionCurveLinear / / uniformCopy the code

    I created four orange UIViews on the demo, passed in these four different arguments, and let all four views move up the Y-axis at the same time.

    [self animatedView: _view1]; [self animatedView: _view2]; [self animatedView: _view3]; [self animatedView: _view4]; // Move view up 250 - (void)animatedView: (UIView *)view {[UIView animateWithDuration: 0.5 delay: 0 options: UIViewAnimationOptionCurveLinear animations: ^{ CGPoint center = view.center; center.y -= 250; view.center = center; } completion: nil]; }Copy the code



    Four linear velocity representations

    In the emulator running state, click the above menu bar DEBUG -> Slow Animation or the shortcut command + T, which will Slow down the Animation running speed of our app (demo runs on the 6P emulator). In the deceleration environment, we see the speed changes of the four Views as follows: 1. Gradual acceleration. EaseIn 2. Speed up first, then slow down. EaseInOut 3. Lead and slow down. EaseOut 4, uniform motion. Linear runs the initial login animation and slows down the animation speed of the emulator. You can see that the EaseInOut parameter used by default causes the password box to slow down significantly near the end point.

  • In addition to the effects mentioned above, we can also use the following parameters to achieve special animation effects when switching views and images.

    UIViewAnimationOptionTransitionNone / / doesn't work, The default UIViewAnimationOptionTransitionFlipFromLeft / / left rollover effect UIViewAnimationOptionTransitionFlipFromRight / / rollover effect from the right UIViewAnimationOptionTransitionCurlUp / / flip down on UIViewAnimationOptionTransitionCurlDown / / pages from down to up UIViewAnimationOptionTransitionCrossDissolve / / the old views dissolve transition to the next view UIViewAnimationOptionTransitionFlipFromTop / / from the rollover effect UIViewAnimationOptionTransitionFlipFromBottom / / from the rollover effectCopy the code

    So when should these parameters be used? Let’s take a look at this code:

    [UIView transitionWithView: firstPV duration: 0.5 options: UIViewAnimationOptionTransitionFlipFromLeft animations: ^{ [firstPV flipCard]; } completion: ^(BOOL finished) { isAnimating = NO; }]; - (void)flipCard { if (isfliped) { self.image = [UIImage imageNamed: @"flipPicBG.png"]; isfliped = NO; } else { self.image = [UIImage imageNamed: [NSString stringWithFormat: @"flipPic%d.png", type]]; isfliped = YES; }}Copy the code

    In this code I’ve changed the image display of a UIImageView, again using an animation. A new animation API method is used here, transitionWithView: Duration: Options: animations: Completion: : This method adds a UIView parameter to the previous animateWithDuration series of methods, which receives an object that acts as the animator. This code is a card matching game I did before, after clicking the animation effect is as follows:




    Turn card match small game

    After using Command +T to slow down the animation in the simulator, I captured four flipped images:




    Slow motion flip

    When we switch images, the original image will be flipped on the X-axis based on the center position of the view. In order to achieve a more realistic effect, the system also adds a shadow effect for us in the switch (PS: Again, you should only animate transition between views — you won’t have any transition effects while moving.

Spring animation

Congratulations, you can now create beautiful animations using UIKit animation interface. You can create real animations by combining different options parameters. But we can always do more, like a spring that is squashed so hard that it bounces back and forth when released. Even if the above method can be used to achieve such animation, but the amount of code is complex, and basically no reuse at all, can be imagined as bad code. Therefore, we need another way to animate, and the system just provides one for us to use:

+ (void)animateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay usingSpringWithDamping:(CGFloat)dampingRatio initialSpringVelocity:(CGFloat)velocity options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^ __nullable)(BOOL finished))completionCopy the code

As usual, additional parameter information:

  • DampingRatio: velocity decay ratio. The value ranges from 0 to 1. The lower the value, the stronger the vibration
  • Velocity: Initialization speed, the higher the value, the faster the item

When a button with a rounded corner moves into the screen at high speed and then vibrates hard, it will definitely catch your eye. For example, when I try to get a UICollectionView’s category button to pop from the bottom of the screen into the view; Or I pop the ball into the bottom right corner to remind the user what to do:




Ball pop-up effect

The effect is very good, after seeing the little ball, you instinctively want to click the button, and the ball pop-up animation is just a few lines of code:

CGPoint center = cell.center; CGPoint startCenter = center; startCenter.y += LXD_SCREEN_HEIGHT; cell.center = startCenter; [UIView animateWithDuration: 0.5 delay: 0.35 * indexPath. Item usingSpringWithDamping: 0.6 initialSpringVelocity: 0 options: UIViewAnimationOptionCurveLinear animations: ^{ cell.center = center; } completion: nil];Copy the code

In addition to the pop-up code, when the ball is clicked, an animation is generated that bounces to the bottom right and then pops up the list from the left. This is cool, because without extra prompting, the user will automatically know how to get back to the group screen by clicking the round button in the bottom right corner. This is very important. Our animation should not only make the interface more elegant and beautiful, but also reduce the cost of users learning to use the app. All these are the pursuit of animation.

The last

Compared with the rough PC terminal, mobile terminal application needs to be more delicate, delicate and complex animation is from a simple animation combination. As the first blog post of animation, this article aims to start with the simplest UIView animation and gradually expand the other animations, and also hope to play a role in the introduction of jade. At the end of this article, if you’re new to iOS animation, try adding code to the login demo at the beginning of this article that makes the buttons pop up from below in a gradient:




The login button is displayed

Last but not least, gitcafe. I originally thought that after hosting in Gitcafe, personal blog in China will improve the speed of access, but today the blog was updated for two hours, but still can not show.

This article demo reprint please indicate the source