简体   繁体   English

NSTextView:以编程方式设置文本格式

[英]NSTextView: format text programmatically

How can I format parts of a text in a NSTextView programmatically? 如何以编程方式在NSTextView中格式化文本的一部分? For example, make all occurrences of the word "foo" blue or make all the text grey but the current paragraph (where the cursor is) solid black? 例如,使所有出现的“ foo”一词变为蓝色,或者使所有文本变为灰色,但当前段落(光标所在的位置)为纯黑色? Thanks 谢谢

You can use NSAttributedString or NSMutableAttributedString just specify text format (color, text size, etc) and pass it to your NSTextView, for example: 您可以使用NSAttributedStringNSMutableAttributedString指定文本格式(颜色,文本大小等),然后将其传递给您的NSTextView,例如:

    NSString *str = @"test string";
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString: str];
    NSDictionary *attributes = @{
                                 NSForegroundColorAttributeName : [NSColor redColor],
                                 NSFontAttributeName : [NSFont fontWithName:@"HelveticaNeue-Bold" size:12.0]
                                 };
    [attrString setAttributes:attributes range:NSMakeRange(0, str.length)];

    [[self.myNSTextView textStorage] appendAttributedString: attrString];

That will set up all your text to be the same but just replace range attribute with the one you want to change only this part of the text: NSMakeRange(0, 2) this will add just the text attributes to first two lerrers. 这样会将所有文本设置为相同,但只将range属性替换为您只想更改文本这一部分的属性即可: NSMakeRange(0, 2)这将仅将文本属性添加到前两个提示中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM