如何更改NSTextView的文本颜色

时间:2022-12-14 20:29:28

How can I change the color of all text in a NSTextView? In the example below, myTextView.textColor = .white only changes color of Hello but not World. I don't want to specify the color every time when I append some text.

如何更改NSTextView中所有文本的颜色?在下面的例子中,myTextView。白色只会改变Hello的颜色,而不会改变世界。我不想每次添加文本时都指定颜色。

Also I'm not sure if this is an appropriate way appending text to NSTextView.

我也不确定这是否是将文本附加到NSTextView的合适方法。

    override func viewDidLoad() {
        super.viewDidLoad()

        myTextView.string = "Hello"
        myTextView.backgroundColor = .black
        myTextView.textColor = .white

        logTextView.textStorage?.append(NSAttributedString(string: "World"))
    }

1 个解决方案

#1


1  

NSTextStorage is a subclass of NSMutableAttributedString so you can manipulate it as a mutable attributed string.

NSTextStorage是一个NSMutableAttributedString的子类,所以您可以将其作为一个可变的带属性字符串进行操作。

If you want the new text to carry on the attributes at the end of the current text, append to the mutable string:

如果您想让新文本在当前文本的末尾继承属性,请附加到可变字符串:

myTextView.textStorage?.mutableString.append("World")

If you want to add more attributes to the new text (for example, adding an underline), get the attributes at the end of the current text and manipulate the attributes dictionary:

如果您想向新文本添加更多的属性(例如,添加下划线),请获取当前文本末尾的属性并操作属性字典:

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))

After this, if you call mutableString.append, the new text will be in white and underlined.

之后,如果你调用mutableString。附加,新的文本将是白色和下划线。

#1


1  

NSTextStorage is a subclass of NSMutableAttributedString so you can manipulate it as a mutable attributed string.

NSTextStorage是一个NSMutableAttributedString的子类,所以您可以将其作为一个可变的带属性字符串进行操作。

If you want the new text to carry on the attributes at the end of the current text, append to the mutable string:

如果您想让新文本在当前文本的末尾继承属性,请附加到可变字符串:

myTextView.textStorage?.mutableString.append("World")

If you want to add more attributes to the new text (for example, adding an underline), get the attributes at the end of the current text and manipulate the attributes dictionary:

如果您想向新文本添加更多的属性(例如,添加下划线),请获取当前文本末尾的属性并操作属性字典:

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))

After this, if you call mutableString.append, the new text will be in white and underlined.

之后,如果你调用mutableString。附加,新的文本将是白色和下划线。