objective-c - 如何获取 -textStorageDidProcessEditing :? 内可见的字符范围

标签 objective-c cocoa syntax-highlighting appkit nslayoutmanager

对于我的语法突出显示实现,我观察到 NSTextView 的更改使用-[<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 ...
}

我想获取可见字符的范围。上面的代码一直有效,直到我按下 退格键,这导致它崩溃:

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

如何获取可见字符的范围以便为它们着色?

最佳答案

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

NSRange range = NSRangeFromString(string);

关于objective-c - 如何获取 -textStorageDidProcessEditing :? 内可见的字符范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8854688/

相关文章:

iphone - 使用动画从相机中移除滤镜 (GPUImage)

html - HTML5 中的实时 SQL 语法高亮显示

swift - 将数据传递给由外部事件触发的 ViewController

syntax-highlighting - Silverstripe 的 Coda 语法高亮显示

python - 如何在 VS 代码中获得 VS 的 python 语法高亮显示?

ios - 如何理解“当使用带有__weak限定词的变量时,该对象总是在autoreleasepool中注册”

objective-c - 对象 C : Grouping strings into NSMutableDictionary

iOS计时器/工资计算器

objective-c - NSTextView 黄色突出显示像在 safari 搜索中

macos - 在 OS X 中谁拥有模型、NSDocument 或 NSViewController