![](/img/trans.png)
[英]Title color of UIButton won't change on highlighted/selected but background color will
[英]iOS button title color won't change
我正在使用以下代碼動態創建一個 UIButton,它按照指定的樣式創建它。
let frame = CGRect(x: 10, y: 6, width: 60, height: 30 )
let button = UIButton(frame: frame)
button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
button.backgroundColor = UIColor.whiteColor()
button.addTarget(self, action: "filterByCategory:", forControlEvents: UIControlEvents.TouchUpInside)
self.categoryScrollView.addSubview(button)
使用此按鈕,我想在點擊時切換樣式。 以下代碼更改背景顏色但不更改標題顏色。 知道為什么標題顏色不會改變嗎?
func filterByCategory(sender:UIButton) {
if sender.backgroundColor != UIColor.blackColor() {
sender.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Selected)
sender.backgroundColor = UIColor.blackColor()
} else {
sender.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
sender.backgroundColor = UIColor.whiteColor()
}
}
因為你的按鈕會變成回UIControlState.Normal
你觸摸后,它成為.Highlighted
,然后.Normal
你應該設置sender.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Selected)
至
sender.setTitleColor(UIColor.whiteColor(), forState: UIControlState. Normal)
或者,只是為所有狀態設置它,因為你檢查了顏色
sender.setTitleColor(UIColor.whiteColor(), forState: [.Normal,.Selected,.Highlighted])
*編輯:上面不起作用,可以使用NSAttributedString
代替
if self.loginButton.backgroundColor == UIColor.blackColor() {
let tittle = NSAttributedString(string: "Login", attributes: [NSForegroundColorAttributeName: UIColor.blackColor()])
loginButton.setAttributedTitle(tittle, forState: .Normal)
loginButton.backgroundColor = UIColor.whiteColor()
} else {
let tittle = NSAttributedString(string: "Login", attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])
loginButton.setAttributedTitle(tittle, forState: .Normal)
loginButton.backgroundColor = UIColor.blackColor()
}
我已經找到超過 4 到 5 個小時的解決方案,但沒有找到任何東西並得出以下兩點結論:-
對於斯威夫特3
button.setTitleColor(.black, for: .normal)
從上面描述的問題。 我得出的結論是您創建的按鈕沒有標題,因此您看不到標題顏色的變化。
要解決此問題:-
button.setTitleColor(.black, for: .normal)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.