How to get the range of characters that are visible from within -textStorageDidProcessEditing:?

孤街醉人 提交于 2019-12-11 01:58:42

问题


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 ...
}

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

How would I get the range of visible characters so I can color them?


回答1:


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);


来源:https://stackoverflow.com/questions/8854688/how-to-get-the-range-of-characters-that-are-visible-from-within-textstoragedidp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!