我正在开发一个使用 NSTextView 的 Cocoa 文本编辑器。是否可以更改文本某些部分的颜色?
5 回答
您应该将控制器添加为( )NSTextStorage
对象的委托,然后实现委托方法。每当文本更改时都会调用它。NSTextView
[textView textStorage]
‑textStorageDidProcessEditing:
在委托方法中,您需要NSTextStorage
使用. 是视图的子类,包含视图的属性内容。-textStorage
NSTextView
NSTextStorage
NSAttributedString
然后,您的代码必须解析字符串并将颜色应用于您感兴趣的任何文本范围。您可以使用类似这样的方法将颜色应用于范围,这会将黄色应用于整个字符串:
//get the range of the entire run of text
NSRange area = NSMakeRange(0, [textStorage length]);
//remove existing coloring
[textStorage removeAttribute:NSForegroundColorAttributeName range:area];
//add new coloring
[textStorage addAttribute:NSForegroundColorAttributeName
value:[NSColor yellowColor]
range:area];
如何解析文本取决于您。NSScanner
是解析文本时使用的有用类。
请注意,此方法绝不是处理语法着色的最有效方法。如果您正在编辑的文档非常大,您很可能需要考虑将解析工作转移到单独的线程和/或巧妙地考虑重新解析哪些文本部分。
Rob Keniger 的回答很好,但对于寻找更具体示例的人来说,这是我写的一个简短的语法荧光笔,它应该突出显示 RegEx 模板语法。我想\
变灰,紧随其后的角色变黑。我想$
变成红色,紧跟在后面的数字字符$
也是红色的。其他一切都应该是黑色的。这是我的解决方案:
我制作了一个模板荧光笔类,其标题如下所示:
@interface RMETemplateHighlighter : NSObject <NSTextStorageDelegate>
@end
我在 nib 文件中将它初始化为一个对象,并通过一个插座将它连接到我的视图控制器。在awakeFromNib
视图控制器中,我有这个(replacer
我的NSTextView
出口在哪里,是templateHighlighter
上面类的出口):
self.replacer.textStorage.delegate = self.templateHighlighter;
我的实现如下所示:
- (void)textStorageDidProcessEditing:(NSNotification *)notification {
NSTextStorage *textStorage = notification.object;
NSString *string = textStorage.string;
NSUInteger n = string.length;
[textStorage removeAttribute:NSForegroundColorAttributeName range:NSMakeRange(0, n)];
for (NSUInteger i = 0; i < n; i++) {
unichar c = [string characterAtIndex:i];
if (c == '\\') {
[textStorage addAttribute:NSForegroundColorAttributeName value:[NSColor lightGrayColor] range:NSMakeRange(i, 1)];
i++;
} else if (c == '$') {
NSUInteger l = ((i < n - 1) && isdigit([string characterAtIndex:i+1])) ? 2 : 1;
[textStorage addAttribute:NSForegroundColorAttributeName value:[NSColor redColor] range:NSMakeRange(i, l)];
i++;
}
}
}
所以你去,一个完整的例子。有一些细节让我绊倒了大约 10 分钟,例如您必须从 textStorage 中取出字符串才能访问各个字符……也许这可以节省其他人几分钟。
我建议您首先阅读有关语法高亮的CocoaDev 页面。很多人都为各种目标提供了解决方案。
如果你想执行源代码语法高亮,我建议你看看Uli Kusterer的UKSyntaxColoredTextDocument 。
如果你对 WebView 没问题,你可以使用https://github.com/ACENative/ACEView
它在 WebView 中加载ACE 编辑器