UI Animation is a great API feature that can vitalize your app in unique ways that can bolster user interaction, add a sense of excitement, and enrich user’s experience. Adding UI Animation in your code is quite simple and can be done with just a few lines of code.
In this example we’ll animate a color change to a button just by simply tapping on it.
Below is a screen shot of a basic set up of a for the “Press Me” UI Button layout with an empty IBAction attached to it.
First Step: Call the UIView.animate method inside the IBAction button.
The first parameter key (withDuration) means how long you want the animation to run for. The second parameter key (Delay) is how long you want the animation to wait before it begins after it was triggered. The third key (options) is the style of animation meaning how you want your animation to speed up and slow down at certain points. I chose curveEaseIn which means the animation begins slowly then speeds up as it progress to the end. There are different options to choose from and you can read all about them in the Apple Developer Documentation. The fourth parameter key is the animation itself where we set the color of the button that we want to change to. This we will fill in at step two of the process. Completion can be left with nil.
Step Two: Set up constants to generate random numbers for RGB Colors.
RGB colors are generated by decimal code values. Red, Green, and Blue with a min value of 0 and a max value of 255. Each color parameter will appear like this i.e (220.0/255, 20.0/255, 60.0/255). The red is 220.0, green is 20.0, and blue is 60.0. This is the color of Crimson. So in this case I’ll use Int.Random method to generate random values from 0 to 255. The code below will appear as…
So what these lines are saying — choose a random integer in values between 0 and less than 256. We’ll set it to 256 to include 255 in the range. Since we’re dealing with UIColors the numbers must be of type CGFloat in order to properly display the right color. To convert the type from Int to a CGFloat type wrap the line around with a CGFloat( ) parameter. So now we have our color constants set up. We’ll need to pass them inside the UIColor parameters in the animations parameter key in the block.
So in the animations parameter we’ll initiate the self.button.backgroundColor to a new random UIColor. In each parameter we’ll carefully place the constant it should correspond to. Red/255 Green/255 … so on forth. The alpha is the measurement of opacity. You can leave it at 1.
And there you go. Run the application and give your button a tap. Random colors should generate. There’s a lot more to what I’ve shown you about UI Animation. I hope this simple tutorial provide you the enough understanding to some finishing touches to your app. It was fun explore this feature.
Thanks for the read. Feel free to comment below if you have anything specific you want to read about in CodersUnited.