Search code examples
iosswiftuser-interfacestoryboardinterface-builder

How to change a button's background color


In this Swift code that I have greatly simplified for posting here:

@IBOutlet weak var outTrig: UIButton!
@IBAction func actTriggerCameras(_ sender: UIButton) {
    Trig()
}

Trig(){
    outTrig.backgroundColor = UIColor.systemRed
}

I attempt to change the Storyboard button's background color to give feedback to the user that touching it registered with the system. But the background color does not change in the iPhone 14 where this code is run. What do I need to do make this change show on the User Interface?


Solution

  • iOS 15 introduced UIButton.Configuration

    By default, when you add a button in Storyboard, the button Style is set to Plain.

    enter image description here

    If the style is Plain, Gray, Tinted or Filled:

    enter image description here

    you have to use its .configuration property to make changes:

    var cfg = outTrig.configuration
    cfg?.baseBackgroundColor = .systemRed
    outTrig.configuration = cfg
    

    If you change the style to Default:

    enter image description here

    enter image description here

    you can then use the "older" methods:

    outTrig.backgroundColor = .systemRed
    

    See Apple's docs here.