2016-12-01 56 views
2

我試圖改變UIButton的文本顏色編程上斯威夫特3.爲什麼我無法更改UIButton文本顏色?

我在其它按鈕做了,但只有有一個在整個項目中,我不能改變顏色,我找不到爲什麼(我可以從故事板手動更改它,但我需要以編程方式更改它的顏色)。要更改字體顏色在其他按鈕我也做了以下內容:

customButton.tintColor = UIColor.red 

,而且運作良好。除了我在UITableViewCell之內的一個UIButton,其中我無法以編程方式將文本顏色更改爲UIButton。不過,我可以手動更改它(使用故事板)。

這是我自定義UITableViewCell代碼:

@IBOutlet weak var customButton: UIButton! 

override func awakeFromNib() { 
    super.awakeFromNib() 

    customButton.tintColor = UIColor.blue 
    customButton.backgroundColor = UIColor.yellow 
} 

但它只是改變了背景顏色爲黃色。

這是我的故事板的配置(我不知道它是否能夠適合此目的):

enter image description here

我知道,這UIButton連接是否正常工作很好,因爲背景顏色正在改變,但隨後,

爲什麼我無法更改其文本顏色?我錯過了什麼嗎?

在此先感謝!

回答

2

問題

設置tintColor僅適用於buttonType = .custom。當您使用UIButton()一個按鈕的默認buttonType.system這將覆蓋全球titleLabeltintColor由於與配置的具體states

解決方案

如果你想褪色titleLabel當系統UIButton的行爲按下按鈕,您需要設置titleColor每個國家象下面這樣:

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

否則,你可以使用.custom並直接設置tintColor

let button = UIButton(type: .custom) 
button.tintColor = UIColor.red 
+0

現在它可以工作,但我不明白爲什麼。在我的項目的其餘按鈕中,我可以使用'customButton.tintColor = UIColor.red'直接更改它。這裏爲什麼不同?或者它與按鈕的__狀態有關,我不明白你的意思是什麼? –

+0

@ Error404編輯 – EridB

+1

謝謝!最後,故事板是錯誤的線索。 –

0

你可以改變它的標題一樣,直接:

let button = UIButton() 
button.titleLabel?.textColor = .red 
+0

這也不起作用。我有手動創建的UIButton。我只需要以編程方式更改其文本顏色屬性。 –

1

如果你想使用TintColor作爲標題顏色,類型應該是System而不是Custom

+0

謝謝!我知道這應該是一件荒謬的事情。 –