根据 Stack Overflow 上的这篇文章 大概有三种方法:
1. 先设置整个 text 为 NSMutableAttributedString, 再使用 Range 设置要改变颜色(字体)的文本
var myString:NSString = "I AM KIRIT MODI"
var myMutableString = NSMutableAttributedString()
In ViewDidLoad
override func viewDidLoad() {
myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))
// set label Attribute
labName.attributedText = myMutableString
super.viewDidLoad()
}
2. 使用 html 文本设置每段文本
Swift4:
let htmlString = "This is some text!"
let encodedData = htmlString.data(using: String.Encoding.utf8)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
label.attributedText = attributedString
} catch _ {
print("Cannot create attributed String")
}
3. 单独设置每段的文本, 再拼接
Swift4:
let attrs1 = [NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedStringKey.foregroundColor : UIColor.green]
let attrs2 = [NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedStringKey.foregroundColor : UIColor.white]
let attributedString1 = NSMutableAttributedString(string:"Drive", attributes:attrs1)
let attributedString2 = NSMutableAttributedString(string:"safe", attributes:attrs2)
attributedString1.append(attributedString2)
self.lblText.attributedText = attributedString1