iOS按钮标题颜色不会改变

问题描述 投票:0回答:5

我正在使用以下代码动态创建一个 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()
    }

}
ios swift xcode7
5个回答
19
投票

因为你的按钮在你触摸之后会变回

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

3
投票

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

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

1
投票

对于 swift 3

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

0
投票

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

解决问题:-

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

0
投票

对于斯威夫特

button.configuration?.baseForegroundColor = UIColor.yellow
© www.soinside.com 2019 - 2024. All rights reserved.