如何更改NSTextView中所有文本的颜色?在下面的示例中,myTextView.textColor = .white
仅更改Hello
但不更改World
的颜色。我每次附加一些文字时都不想指定颜色。
此外,我不确定这是否适合将文字附加到NSTextView。
override func viewDidLoad() {
super.viewDidLoad()
myTextView.string = "Hello"
myTextView.backgroundColor = .black
myTextView.textColor = .white
logTextView.textStorage?.append(NSAttributedString(string: "World"))
}
答案 0 :(得分:1)
NSTextStorage
是NSMutableAttributedString
的子类,因此您可以将其作为可变属性字符串进行操作。
如果您希望新文本在当前文本末尾继承属性,请附加到可变字符串:
myTextView.textStorage?.mutableString.append("World")
如果要为新文本添加更多属性(例如,添加下划线),请获取当前文本末尾的属性并操作属性字典:
guard let textStorage = myTextView.textStorage else {
return
}
var attributes = textStorage.attributes(at: textStorage.length - 1, effectiveRange: nil)
attributes[.underlineStyle] = NSNumber(value: NSUnderlineStyle.styleSingle.rawValue)
textStorage.append(NSAttributedString(string: "World", attributes: attributes))
在此之后,如果您拨打mutableString.append
,则新文字将为白色并带下划线。