我正在使用以下代码动态创建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)
Run Code Online (Sandbox Code Playgroud)
使用此按钮,我想在点击时切换样式.以下代码更改背景颜色,但不更改标题颜色.知道为什么标题颜色不会改变?
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()
}
}
Run Code Online (Sandbox Code Playgroud)
Tj3*_*j3n 13
因为您的按钮会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()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5506 次 |
| 最近记录: |