我正在使用以下代码动态创建一个 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 个小时的解决方案,但没有找到任何东西并得出这两点结论:-
对于 swift 3
button.setTitleColor(.black, for: .normal)
从上面描述的问题。 我得出的结论是您创建的按钮没有标题,因此您看不到标题颜色的变化。
解决问题:-
button.setTitleColor(.black, for: .normal)
对于斯威夫特
button.configuration?.baseForegroundColor = UIColor.yellow