在对AttributedString/Substring类型进行扩展时,不能将其下标设置为可写的。可以使用方法或者计算属性来代替下标进行操作。
例如,将下标操作改写为方法:
extension AttributedString {
func setAttribute(_ attribute: NSAttributedString.Key, value: Any, range: NSRange) -> AttributedString {
let mutableAttributedString = NSMutableAttributedString(attributedString: self)
mutableAttributedString.addAttribute(attribute, value: value, range: range)
return AttributedString(mutableAttributedString)
}
}
let attributedString = AttributedString("Hello, world!")
let range = NSRange(location: 0, length: 5)
let coloredString = attributedString.setAttribute(.foregroundColor, value: UIColor.red, range: range)
或者使用计算属性:
extension AttributedString {
var foregroundColor: UIColor? {
get {
return attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor
}
set {
if let color = newValue {
addAttribute(.foregroundColor, value: color, range: NSRange(location: 0, length: length))
} else {
removeAttribute(.foregroundColor, range: NSRange(location: 0, length: length))
}
}
}
}
let attributedString = AttributedString("Hello, world!")
attributedString.foregroundColor = UIColor.red