属性字符串的Swift标题更改颜色仍为默认蓝色

时间:2018-06-13 08:16:49

标签: swift

在这里检查了很多主题,但找不到解决方案让它发挥作用。

带有属性文字的按钮不会更改其文本颜色。

代码的最终版本:

let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.center

let forgotCodeAttributedTitle = NSMutableAttributedString(string: "forgot_code_2_lines".localized(),
                                                       attributes: [ kCTParagraphStyleAttributeName as NSAttributedString.Key: style])

forgotCodeAttributedTitle.addAttribute(kCTForegroundColorAttributeName as NSAttributedStringKey, value: Colors.BTN_FORGOT_CODE_TEXT_COLOR, range: NSMakeRange(0, forgotCodeAttributedTitle.string.count))

btnForgotCode.setAttributedTitle(forgotCodeAttributedTitle, for: .normal)

1 个答案:

答案 0 :(得分:1)

将其用于NSMutableAttributedString attributes参数:

attributes: [NSAttributedStringKey.paragraphStyle: style]

并将你的`addAttribute代码更改为:

let forgotCodeAttributedTitle = NSMutableAttributedString(string: "forgot_code_2_lines", attributes: [NSAttributedStringKey.paragraphStyle: style])

或者,更简单的是,使用此代码在单个语句中设置段落样式和前景色:

let forgotCodeAttributedTitle = NSMutableAttributedString(string: "forgot_code_2_lines", attributes: 
    [NSAttributedStringKey.paragraphStyle: style, 
     NSAttributedStringKey.foregroundColor: UIColor.red])