NSTextView语法高亮 [英] NSTextView syntax highlighting

查看:408
本文介绍了NSTextView语法高亮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个NSTextView的Cocoa文本编辑器。是否可以更改文本某些部分的颜色?

I'm working on a Cocoa text editor which uses an NSTextView. Is it possible to change the color of certain portions of the text?

推荐答案

您应该将控制器添加为 NSTextStor ( [textView textStorage] )的然后实现委托方法 -textStorageDidProcessEditing:

You should add your controller as the delegate of the NSTextStorage object of the NSTextView ([textView textStorage]) and then implement the delegate method ‑textStorageDidProcessEditing:. This is called whenever the text changes.

在委托方法中,您需要从中获取当前的 NSTextStorage 对象文本视图使用 NSTextView -textStorage 方法。 NSTextStorage NSAttributedString 的子类,包含视图的属性内容。

In the delegate method you need to get the current NSTextStorage object from the text view using the -textStorage method of NSTextView. NSTextStorage is a subclass of NSAttributedString and contains the attributed contents of the view.

然后,您的代码必须解析字符串,并对您感兴趣的任何文本范围应用着色。您可以使用类似这样的颜色应用颜色到整个字符串的黄色:

Your code must then parse the string and apply coloring to whatever ranges of text are interesting to you. You apply color to a range using something like this, which will apply a yellow color to the whole string:

//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 是解析文本时使用的一个有用的类。

How you parse the text is up to you. NSScanner is a useful class to use when parsing text.

请注意,此方法绝不是最有效的处理语法着色的方式。如果你正在编辑的文档非常大,你很可能想考虑将解析卸载到一个单独的线程和/或聪明的文本的哪些部分被重新解析。

Note that this method is by no means the most efficient way of handling syntax coloring. If the documents you are editing are very large you will most likely want to consider offloading the parsing to a separate thread and/or being clever about which sections of text are reparsed.

这篇关于NSTextView语法高亮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆