Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I not able to change UIButton text-color?

I am trying to change the text-color of an UIButton programmatically on Swift 3.

I have done it in other buttons but there is only one in the whole project that I cannot change the color and I cannot find why (I can change it manually from storyboard but I need to change its color programmatically). To change the text-color in other buttons I have done the following:

customButton.tintColor = UIColor.red

and it works well. Except one UIButton that I have inside an UITableViewCell in which I cannot change the text-color to that UIButton programmatically. I can change it manually (using storyboard), although.

This is the code that I have for the custom UITableViewCell:

@IBOutlet weak var customButton: UIButton!

override func awakeFromNib() {
    super.awakeFromNib()
    
    customButton.tintColor = UIColor.blue
    customButton.backgroundColor = UIColor.yellow
}

but it only changes the background color to yellow.

This is my storyboard configuration (that I do not know if it can be relevant for this purpose):

enter image description here

I know that the connection to that UIButton is working well because the background-color is changing but then,

Why am I not able to change its text-color? Am I missing something?

Thanks in advance!

like image 989
Francisco Romero Avatar asked Dec 01 '16 14:12

Francisco Romero


2 Answers

Issue

Setting tintColor works only for buttonType = .custom. When you create a button using UIButton() the default buttonType would be .system which will override your global titleLabel and tintColor due to configuration with specific states

Solution

If you want the behavior of the system UIButton of fading the titleLabel when pressing the button, you need to set the titleColor for each state like below:

let button = UIButton()
button.setTitleColor(UIColor.red, for: .normal)

Otherwise you can use .custom and set tintColor directly.

let button = UIButton(type: .custom)
button.tintColor = UIColor.red
like image 179
E-Riddie Avatar answered Oct 19 '22 23:10

E-Riddie


If you want to use the TintColor as the title Color, the type should be System instead of Custom

like image 29
CZ54 Avatar answered Oct 20 '22 00:10

CZ54