Home > Mobile >  What is the right way to change the title color of a Filled styled UIButton programatically?
What is the right way to change the title color of a Filled styled UIButton programatically?

Time:08-26

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?

CodePudding user response:

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

CodePudding user response:

You can also use the .baseForegroundColor configuration property:

var cfg = tintedBtn.configuration
cfg?.baseForegroundColor = .red
tintedBtn.configuration = cfg
  • Related