UITextView属性文本和语法高亮显示 [英] UITextView attributedText and syntax highlighting
问题描述
因此,对于iOS 6,UITextView可以使用一个referencedString,这对于语法高亮显示非常有用。
So, with iOS 6 an UITextView can take an attributedString, which could be useful for Syntax highlighting.
我在 -textView:shouldChangeTextInRange:replacementText:
中做了一些正则表达式模式,而且我经常需要更改已经输入的单词的颜色。我没有看到除了重置attributesText之外的其他选项,这需要时间。
I'm doing some regex patterns in -textView:shouldChangeTextInRange:replacementText:
and oftentimes I need to change the color of a word already typed. I see no other options than resetting the attributedText, which takes time.
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
//A context will allow us to not call -attributedText on the textView, which is slow.
//Keep context up to date
[self.context replaceCharactersInRange:range withAttributedString:[[NSAttributedString alloc] initWithString:text attributes:self.textView.typingAttributes]];
// […]
self.textView.scrollEnabled = FALSE;
[self.context setAttributes:self.defaultStyle range:NSMakeRange(0, self.context.length)];
[self refresh]; //Runs regex-patterns in the context
textView.attributedText = self.context;
self.textView.selectedRange = NSMakeRange(range.location + text.length, 0);
self.textView.scrollEnabled = TRUE;
return FALSE;
}
这在模拟器上运行得很好,但在iPad 3上每个 -setAttributedText
需要几百毫秒。
This runs okayish on the simulator, but on an iPad 3 each -setAttributedText
takes a few hundreds of milliseconds.
我向Apple提交了一个错误,要求能够改变它attributedText。它被标记为重复,所以我看不出他们对此有何看法。
I filed a bug to Apple, with the request of being able to mutate the attributedText. It got marked as a duplicate, so I cannot see what they're saying about this.
更具体的问题:
如何在UITextView中更改某些范围的颜色,其中包含大量多色文本,并且在每个 shouldReplaceText ...
?
更广泛的问题:
如何进行语法突出显示在iOS 6中使用UITextView?
The more broad question: How do you do syntax highlighting with a UITextView in iOS 6?
推荐答案
attributionText访问器必须往返于HTML的往返,所以它实际上是非最适合语法突出显示的文本视图实现。在iOS 6上,您可能希望直接使用CoreText。
The attributedText accessors have to round-trip to/from HTML, so it's really non-optimal for a syntax-highlighted text view implementation. On iOS 6, you'll probably want to use CoreText directly.
这篇关于UITextView属性文本和语法高亮显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!