NSTextView:以编程方式格式化文本

时间:2015-09-01 08:20:06

标签: objective-c swift cocoa nstextview

如何以编程方式格式化NSTextView中的部分文本?例如,将所有出现的单词“foo”设为蓝色或使所有文本为灰色但当前段落(光标所在的位置)为纯黑色? 感谢

1 个答案:

答案 0 :(得分:1)

您可以使用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];

这会将您的所有文本设置为相同,但只需将范围属性替换为您只想更改文本的这一部分: NSMakeRange(0, 2)这会将文本属性添加到前两个lerrers。

相关问题