Animations plays an important role in mobile app, as an app with animation looks more appealing with a cool design. We can animate any control inherited from UIView class in iOS SDK using different methodologies or classes provided within the iOS SDK. In this tutorial, we will learn how to animate uilabel using CATransition to achieve animation effect like counter increment and decrement. Though you can use, UIView animation methods like
Using the above approach does not provide more control to the developer as the developer can write the code inside the animate block. Thus functionlity only limited to animate a UIView either by setting the properties like hidden, alpha or changing the frame.
startProgress: Specify the progress of animation to begin at, value should be in range of 0 to 1. Example, default is 0 and animation starts from very beginning of transition. If the
startProgress value set to 0.5 then the animation will start when transition is in the half way stage.
endProgress: Simlar to
startProgress, but it specify the progress of transition at which animation should stop. The value should be greater then
startProgress and default is set to 1.
How to use CATransition animation on UILabel
1: Create a single view application project using xcode. Open “Main.storyboard”, and create an user interface as shown in the image below
2: Open “ViewController.swift” , and create IBOutlet, IBAction’s for the UILabel and UIButton’s respectively as shown here
3: Open “Main.storyboard” , and connect the IBOutlet and IBAction’s. Connect incrementCounter to “+” UIButton and decrementCounter to “-” UIButton.
4: Open “ViewController.swift” and add the below animation code as an extension.
If you look at the animation code we have two functions,
i) bottomAnimation
ii) topAnimation
First, we create an object using
CATransition class. Then assign the CAtransition object
timingFunction property which control the speed of animation. Assign duration, type, subType and finally add the animation to the layer.
Both the codes had almost same code and the only difference is the “subType” specified for the animation direction. “bottomAnimation” function had direction for animation “from Top” as specified in “subType“property of the transition and “topAnimation” function had direction for animation “from Bottom” as specified in “subType“property of the transition.
Using the bottomAnimation and topAnimation
Now lastly use the function’s added to CALayer as an extension. Below is the code that shows how to use the “bottonAnimation” and “topAnimation” functions. First, we will create variable named “counter”, which will act as our counter as it will be incremented and decremented when we click on “+” and “-” button’s respectively.
Where to go from here
In this tutorial, we learned about CATransition class and it’s properties. Benefit of using CATransition animation. Also we, learned how add counter animation to UILable using CATransition animation.