我试图将string
放在图像和文字都较小的按钮上,所以我正在使用NSMutableAttributedString
和NSAttributedString
。据我所知,字典中的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!)
答案 0 :(得分:1)
如果您不打算在文本中使用不同的颜色,则可以选择使用UIButton的方法来对事物进行着色:
thumbUpButton?.titleLabel?.textColor = fgColor
thumbUpButton?.backgroundColor = bgColor