斯威夫特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)
NSAttributedString ...请参见http://计算器。com/questions/3482346/how-do-you-use-nsattributedstring –
http://stackoverflow.com/questions/3786528/iphone-ipad-how-exactly-use-nsattributedstring – ajithmn89
你的目标是iOS 6.0及以上版本吗? – Bartu