How do you animate the change of background color of a view on iOS?


In this post we will learn how to change the background color of view with animation.

In this example we will change background color of view on click of a button. On clicking the button the background color will change to red, then on next click it would change to blue, on next click to red again.

Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “ChangeBGColor”

Step 2 − Open Main.storyboard add a button as shown below

Step 3 − Add one @IBAction for touchUpInside of ‘Change Background’ button. Name the function as changeBackgroundClicked.

Step 4 − We will use ‘animate’ function of UIView to change the background color. It provides us the duration and optional completion as parameters. In changeBackgroundClicked we will change the background color of the view from red to blue and vice versa. Add the following code to changeBackgroundClicked

@IBAction func changeBackgroundClicked(_ sender: Any) {
   if self.view.backgroundColor == UIColor.red {
      UIView.animate(withDuration: 2) {
         self.view.backgroundColor = UIColor.blue
      }
   } else {
      UIView.animate(withDuration: 2) {
         self.view.backgroundColor = UIColor.red
      }
   }
}

Step 5 − Run the code, click on the ‘Change Background Color’ button. You should see the background color of the view changing between red and blue with animation.


Updated on: 11-Sep-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements