Change the title color of a Default styled button programmatically is straightforward.
We just need to perform
button.setTitleColor(.red, for: .normal)
But, what about a Filled styled button?
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
You can make a neat little extension to AttributeContainer:
And then use it to set the button’s title and color:
..or you can just do this:
You can also use the
.baseForegroundColor
configuration property: