使用NSAttributedString类和NSMutableAttributedString类来创建和修改带有富文本属性的字符串。
NSAttributedString是一个不可变对象,可以通过构造函数或字面量创建。例如:
// 使用构造函数
let attributedString = NSAttributedString(string: "Hello World!", attributes: [NSAttributedString.Key.foregroundColor : UIColor.red])
// 使用字面量
let attributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.red,
.font: UIFont(name: "HelveticaNeue-Bold", size: 18)!
]
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributes)
NSMutableAttributedString是一个可变对象,可以添加或修改属性。例如:
// 创建NSMutableAttributedString
let mutableAttributedString = NSMutableAttributedString(string: "Hello World!")
// 添加属性
let range = NSRange(location: 0, length: mutableAttributedString.length)
mutableAttributedString.addAttribute(.foregroundColor, value: UIColor.red, range: range)
mutableAttributedString.addAttribute(.font, value: UIFont(name: "HelveticaNeue-Bold", size: 18)!, range: range)
// 修改属性
let rangeToReplace = NSRange(location: 6, length: 5)
mutableAttributedString.replaceCharacters(in: rangeToReplace, with: "Swift")
可以将NSAttributedString赋值给UILabel或UITextView的attributedText属性。例如:
let label = UILabel()
label.attributedText = attributedString
let textView = UITextView()
textView.attributedText = mutableAttributedString