斯威夫特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