在这里检查了许多主题,但找不到使其工作的解决方案。
带有属性文本的按钮不更改其文本颜色。
代码的最终版本:
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)
最佳答案
将此参数用于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])