iOS 按钮标题颜色不会改变

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()
        }

对于 swift 3

button.setTitleColor(.black, for: .normal)

从上面描述的问题。 我得出的结论是您创建的按钮没有标题,因此您看不到标题颜色的变化。

解决问题:-

  1. 设置按钮的标题
  2. 使用 UIButton 更改标题颜色属性button.setTitleColor(.black, for: .normal)

我已经找到了超过 4 到 5 个小时的解决方案,但没有找到任何东西并得出这两点结论:-

  • 如果您从情节提要中提供标题并以编程方式或自定义 class 设置标题颜色,那么它将不起作用。解决方案是
  1. 您可以使用简单的 setTitleColor() 方法以编程方式设置标题并以编程方式更改其颜色。
  2. 或者你可以使用故事板来设置标题和通过前景色设置颜色。
  3. 如果您使用自定义 Class,您可以使用 Inspectable 并以编程方式设置其值,并使用解决方案 1 设置标题颜色。
  • 如果您不想执行此步骤,只需将按钮类型更改为默认值,它将以您以编程方式或从故事板设置 titleColor 的任何方式工作