iOS 按钮标题颜色不会改变 [英] iOS button title color won't change
问题描述
我正在使用以下代码动态创建一个 UIButton,该代码根据指定的样式创建它.
I'm creating a UIButton dynamically with the following code which creates it as per specified style.
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)
使用此按钮,我想在点击时切换样式.以下代码更改背景颜色但不更改标题颜色.知道为什么标题颜色不会改变吗?
With this button, I want to toggle the style when tapped. The following code changes the background color but not the title color. Any idea why title color won't change?
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
Because your button will turn back to UIControlState.Normal
after you touch it, it become .Highlighted
, then .Normal
你应该设置sender.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Selected)
到
sender.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
或者,只需为所有状态设置它,因为您检查了颜色,例如
or, just set it for all the states since u did a check for color like
sender.setTitleColor(UIColor.whiteColor(), forState: [.Normal,.Selected,.Highlighted])
*Edit: 以上不起作用,可以使用 NSAttributedString
代替
* Above doesn't work, can use NSAttributedString
instead
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()
}
这篇关于iOS 按钮标题颜色不会改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!