如何获取从-textStorageDidProcessEditing:?内可见的字符范围 [英] How to get the range of characters that are visible from within -textStorageDidProcessEditing:?

查看:247
本文介绍了如何获取从-textStorageDidProcessEditing:?内可见的字符范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的语法高亮实现,我观察到 NSTextView 使用 - [< NSTextStorageDelegate> textStorageDidProcessEditing:]

For my syntax highlighting implementation, I observe changes to an NSTextView using -[<NSTextStorageDelegate> textStorageDidProcessEditing:].

- (void)textStorageDidProcessEditing:(NSNotification *)notification {
  if (!self.languageGrammar) return;
  NSTextStorage *textStorage = self.textView.textStorage;
  NSRange glyphRange = [self.textView.layoutManager glyphRangeForBoundingRect:self.scrollView.documentVisibleRect
                                                              inTextContainer:self.textView.textContainer];
  NSRange editedRange = [self.textView.layoutManager characterRangeForGlyphRange:glyphRange actualGlyphRange:NULL];

  [textStorage removeAttribute:NSForegroundColorAttributeName range:editedRange];
  // crash is the line above ^^^^
  // color text ...
}

我想获取可见字符的范围。上述代码工作,直到我点击 backspace ,这会导致崩溃:

I want to get the range of visible characters. The above code works until I hit backspace, which makes it crash:

*** -[NSConcreteTextStorage attributesAtIndex:effectiveRange:]: Range or index out of bounds

推荐答案

检查范围是否超出整个字符串的边界,如果设置了适合字符串边界的范围:

Check if the range is beyond the bounds of the entire string, and if it is set the range to fit the bounds of the string:

NSRange range = NSRangeFromString(string);

这篇关于如何获取从-textStorageDidProcessEditing:?内可见的字符范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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