Home > Software engineering >  How to change background color of UIButton
How to change background color of UIButton

Time:05-26

I want to change the color of UIbuttons but problem is that I have tried changing color in

@IBAction func buttonPressed(_ sender: UIButton) {
    sender.backgroundColor = .red
}

it is not doing anything but on the same time some other buttons are changing colors on this method. I am really confused about this behaviour that some buttons are changing color on same method others don't.

I've also tried @IBOutlet method and it also didn't worked

@IBOutlet weak var button: UIButton!

and then change the color of button in method

button.backgroundColor = .red

Even setting text or color of the in viewDidLoad not working. It is showing the same button as it is designed in storyboard

CodePudding user response:

initialize the button like this

@IBOutlet weak var btnname: UIButton!

then in viewdidload or function

btnname.backgroundColor = .red

CodePudding user response:

So finally after hours of work I figure out the all connections are working and I have to set tintColor not a backgroundColor to change button color. I have tried changing tintColor before but I didn't see the change because backgroundColor was overriding it. All this confusion occured because. of two reasons.

1). I imagined that button color is backgroundColor but its was actually tintColor

2). There are almost three variables in storyboard with same backgroundColor as seen in given images which are overriding colors and even color was changing I was unable to see the change. As far as title change is concerned using this line did the trick

sender.setTitle("Button", for: .normal)

instead of this line

sender.titleLabel?.text = "Button"

First Image Second Image

  • Related