UITextView属性文本和语法高亮显示

Joh*_*und 6 syntax-highlighting uitextview nsattributedstring uitextviewdelegate ios6

背景

因此,对于iOS 6,UITextView可以使用一个referencedString,这对于语法高亮显示非常有用.

我正在做一些正则表达式模式,-textView:shouldChangeTextInRange:replacementText:我经常需要更改已经输入的单词的颜色.我认为没有其他选择,只能重置attributesText,这需要时间.

- (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;
}
Run Code Online (Sandbox Code Playgroud)

这在模拟器上运行得很好,但在iPad 3上每个都-setAttributedText需要几百毫秒.

我向Apple提交了一个错误,要求能够改变attributionText.它被标记为重复,所以我看不出他们对此有何看法.

这个问题

更具体的问题: 如何在UITextView中更改某些范围的颜色,使用大量的彩色文本,并且每个都有足够的性能shouldReplaceText...

更广泛的问题: 如何使用iOS 6中的UITextView进行语法突出显示?

小智 0

attributeText 访问器必须往返于 HTML,因此对于语法突出显示的文本视图实现而言,这确实不是最佳选择。在 iOS 6 上,您可能想直接使用 CoreText。