skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    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


  2. initialize the button like this

    @IBOutlet weak var btnname: UIButton!
    

    then in viewdidload or function

    btnname.backgroundColor = .red
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search