› All Posts › programming › How to animate the change of background color of a view on iOS ?

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

· 142 words · 1 minute read

Step by step guide to create background color changing with beautiful animation 🔗

  1. open Main.storyboard add a button as shown below

    create button in main storyboard

  2. add one @IBAction for touchUpInside of ‘Change Background’ button. Name the function as changeBackgroundClicked.

  3. use animate function of UIView to animate the change of 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. Here is the code.

@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
      }
   }
}

Run the app with iPhone simulator in Xcode. And tap on the button, the background color will change from red to blue, and from blue to red with a beautiful transition animation fading.

Abanoub Hanna
Author

Abanoub Hanna

Software developer and founder of KartBusiness

The author is Abanoub Hanna, a graduate of the Faculty of Science, Department of Microbiology and Biochemistry - Sohag University. I work in the software development industry. Founder of the KartBusiness platform, and developer of the Keme PDF app , Keme POS app , Keme Cash app , img2txt OCR app , Agpeya app , Pope Shenouda III Books app , and Keme OCR Text Scanner app , as well as the owner of the Abanoub Hanna website.