Home > Blockchain >  Setting backgroundColor of custom UIButton class has no effect?
Setting backgroundColor of custom UIButton class has no effect?

Time:08-18

I have a UIButton subclass I've created called TimerButton which has two methods to set the color of it:

class TimerButton: UIButton {

    func setRunning() {
        self.backgroundColor = .systemYellow
    }

    func setStopped() {
        self.backgroundColor = .systemMint
    }
}

My TimerButton is also representing in a StoryBoard, where I've set the color to systemMint and added the custom class to the button presented:

enter image description here enter image description here

In my ViewController I have the button linked as an IBAction, and an IBObject called button. I call the methods self.button.setRunning() and self.button.setStopped() in the IBAction that is linked to it in the storyboard based on when its running.

However the color never changes from the systemMint that was set in the Storyboard

How do I get the appropriate color to appear?

CodePudding user response:

You are using a Filled button style, so you need to use the button configuration to change the color:

class TimerButton: UIButton {
    func setRunning() {
        self.configuration?.baseBackgroundColor = .systemYellow
    }
    func setStopped() {
        self.configuration?.baseBackgroundColor = .systemMint
    }
}
  • Related