How to change a button background color using Swift?

iOSiPhone/iPadMobile Development

To change the background color of a button in iOS application we need to access the property ‘ backgroundColor’ of the UIButton. We can do this in two ways, programmatically and using the storyboard.

Method 1 − Using the storyboard editor

Add a button on your storyboard, select it Go to it’s attribute inspector and select 'Background' property to choose the color.

Method 2 − Programmatically changing the background

Create outlet of the button on the View Controller.

In the viewDidLoad() or viewWillLayoutSubview() method add the code to change the background color.

btn.backgroundColor = #colorLiteral(red: 0.4392156899, green:
0.01176470611, blue: 0.1921568662, alpha: 1)

When we run the method one by selecting a color on the attribute inspector, below is the result that’s created.

Published on 21-Jan-2019 12:37:47