Swift 4
(注意:属性字符串键的符号在 swift 4 中更改)
这是 的扩展NSMutableAttributedString
,在字符串/文本上添加/设置颜色。
extension NSMutableAttributedString {
func setColor(color: UIColor, forText stringValue: String) {
let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive)
self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
}
}
现在,尝试上面的扩展UILabel
并查看结果
let label = UILabel()
label.frame = CGRect(x: 40, y: 100, width: 280, height: 200)
let title = "Name"
let star = "*"
let stringValue = "\(title) \(star)"
label.textColor = UIColor.lightGray
label.numberOfLines = 0
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColor(color: UIColor.red, forText: star) // or use direct value for text "red"
label.font = UIFont.systemFont(ofSize: 26)
label.attributedText = attributedString
self.view.addSubview(label)