skip to Main Content

Change the title color of a Default styled button programmatically is straightforward.

enter image description here

We just need to perform

button.setTitleColor(.red, for: .normal)

But, what about a Filled styled button?

enter image description here

Using 1 liner UIButton.setTitleColor has no effect.

After several trial and error, I have came out with an "ugly" way

if let configuration = button.configuration {
    let attributedStringColor = [NSAttributedString.Key.foregroundColor : UIColor.red];

    let attributedString = NSAttributedString(
        string: button.titleLabel?.text ?? "",
        attributes: attributedStringColor
    )

    do {
        let a = try AttributedString(attributedString, including: .uiKit)
        
        var c = configuration
        
        c.attributedTitle = a
        
        button.configuration = c
    } catch {
    }
}

Even though that works, I just feel it is not the right way, to require so many lines of code to change the button title color.

May I know, what is the right way to change the title color of a Filled styled UIButton programmatically?

2

Answers


  1. You can make a neat little extension to AttributeContainer:

    extension AttributeContainer {
        init(foregroundColor: UIColor) {
            self.init()
            self.foregroundColor = foregroundColor
        }
    }
    

    And then use it to set the button’s title and color:

    button.configuration = .filled()
    button.configuration?.attributedTitle = AttributedString("ButtonTitle", attributes: .init(foregroundColor: .systemRed))
    

    ..or you can just do this:

    button.configuration?.attributedTitle?.foregroundColor = .systemRed
    
    Login or Signup to reply.
  2. You can also use the .baseForegroundColor configuration property:

    var cfg = tintedBtn.configuration
    cfg?.baseForegroundColor = .red
    tintedBtn.configuration = cfg
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search