Change Color of Button in iOS when Clicked


Imagine you’re playing a song and as soon as you press the stop button, the color of the button should turn to red. This is one of the many scenario where you might need to change the color of button when it is clicked.

In this tutorial we will see how to change the background color of a button when it is clicked. So let’s get started!

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

Step 2 − In the Main.storyboard create one button and name it stop.

Step 3 − Create @IBAction of the button and @IBOutlet of the button and name it btnChangeBgColor and btnBgColor respectively. Here we are using both action and outlet, because on action of the same button we want to change the property of the same.

Step 4 − In the action of the button type the following code.

@IBAction func btnChangeBgColor(_ sender: Any) {
   self.btnBgColor.backgroundColor = UIColor.red
}

Step 5 − Run the code.

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements