How to programmatically change the button foreground color in Xcode?

802 Views Asked by At

I have a button with a system image and no Title string. I want to programmatically change the foreground color of the system image. I tried

myBtn.setTitleColor(UIColor.systemYellow, for: .normal)

This doesn't work. I know I can change the foreground color using the Interactive Builder. In the button's Attribute Inspector, there's a Foreground field that allows me to change the foreground color, but I can't find the method that accesses that attribute.

Attribute Inspector Picture

Regards, Tim

1

There are 1 best solutions below

0
sveeen98 On

You may need to use the UIButton.Configuration API introduced in iOS 15. Setting the foreground color in the storyboard would set the baseForegroundColor of the configuration, rather than calling setTitleColor(_:for:).

So set the button foreground color with:

myBtn.configuration?.baseForegroundColor = UIColor.systemYellow