UIButton NSAttributedString不会更新字体颜色

时间:2019-03-21 16:02:54

标签: ios swift nsattributedstring nsmutablestring

我试图将string放在图像和文字都较小的按钮上,所以我正在使用NSMutableAttributedStringNSAttributedString。据我所知,字典中的foregroundColor键应该更新文本的颜色,但似乎不起作用。 fgColor是UIColor.white,bgColor是UIColor.black,但我在打印出来进行验证时遇到了麻烦。谁能提供建议?代码是:

let myFont = UIFont(name: "HelveticaNeue-Light", size: 8)
let dict1:[NSAttributedString.Key:Any] = [
        NSAttributedString.Key.font:myFont!,
        NSAttributedString.Key.foregroundColor : fgColor,
        NSAttributedString.Key.strokeColor : fgColor,
        NSAttributedString.Key.backgroundColor : bgColor
]
let fullString = NSMutableAttributedString()
let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(named:"ThumbsUpGreen")
let imageString = NSAttributedString(attachment: imageAttachment)
fullString.append(imageString)
fullString.append(NSAttributedString(string: " "+String(upCount), attributes: dict1))
thumbUpButton?.setAttributedTitle(fullString, for: .normal)
contentView.addSubview(thumbUpButton!)

1 个答案:

答案 0 :(得分:1)

如果您不打算在文本中使用不同的颜色,则可以选择使用UIButton的方法来对事物进行着色: thumbUpButton?.titleLabel?.textColor = fgColor thumbUpButton?.backgroundColor = bgColor