iOS Animation - UIView.AnimationWithDurarion
Learning notes for book iOS Animations by Tutorials.
Logging page is very common in your mobile apps today. A fancy logging page will catch people’s eyes at the very beginning. Let’s do it.
Shifting and Fade in:
The view contains:
- A heading Label shows login page
- A Username textField
- A Password textField
- A Login button
The animation shows that the label comes from left to right first, then follow by the username textField, and then follow by the password textField. The log in button starts to fade in when the password textField starts to come in. The password textField and the login button finish their animation at the same time.
So, what we need to do first is to hide all the components before view starts to appear. In viewWillAppear()
, we do:
1 | // move the following components out of the screen |
After we done in viewWillAppear()
, we start to write down the animation code in viewDidAppear()
, which will show animation before the view fully loaded. Here we will use UIView class method “animateWithDuration”. In viewDidAppear()
, we do:1
2
3
4
5
6
7
8
9
10
11
12UIView.animateWithDuration(1.0, animations: {
self.heading.center.x += self.view.bounds.width;
})
UIView.animateWithDuration(1.0, delay: 0.4, options: [], animations: {
self.username.center.x += self.view.bounds.width;
}, completion: nil)
UIView.animateWithDuration(1.0, delay: 0.8, options: [], animations: {
self.password.center.x += self.view.bounds.width;
}, completion: nil)
UIView.animateWithDuration(1.0, delay: 0.8, options: [], animations: {
self.loginButton.alpha += 1.0
}, completion: nil)
In the class method, it has some parameters to let you customize your animation:
- duration: The duration of the animation.
- delay: A number of seconds UIKit will wait before it starts the animation.
- option: A set of animation options allowing you to customize a number of aspects of your animation. (Default: CurveEaseInOut)
- animation: The closure expression to provide your animation.
- completion: The code needs to be executed after the animation completes. It could be nil.
Spring
Spring is easy. We still use the same class method from UIView animateWithDuration but with different parameters. Codes in
viewDidAppear()
.
1 | UIView.animateWithDuration(1.0, delay: 0.4, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: [], animations: { |
The new parameters are:
- usingSpringWithDamping: You can think of this value as the “stiffness” of the spring.
- initialSpringVelocity: This controls the initial velocity of the animation.
The method animateWithDuration allows you to animate the following properties of a UIView:
- frame
- bounds
- center
- transform
- alpha
- background
- contentStretch