获取并突出显示NSTextView中的当前Word

Dr.*_*eon 7 cocoa objective-c nstextview

好的,这就是我想要的:

  • 我们有一个 NSTextView
  • NSRange在光标位置获取"当前"字(作为?)(如何确定?)
  • 突出显示它(更改其属性)

我不确定如何解决这个问题:我的意思是我的主要关注点是获取当前位置NSTextView并获得关键点(我知道一些Text插件支持这一点,但我不确定原始NSTextView实现... )

那有内置功能吗?或者,如果没有,任何想法?


更新: 光标位置(已解决)

NSInteger insertionPoint = [[[myTextView selectedRanges] objectAtIndex:0] rangeValue].location;
Run Code Online (Sandbox Code Playgroud)

现在,仍在尝试找到指定基础单词的解决方法......

Wev*_*vah 7

这是一种方式:

NSUInteger insertionPoint = [myTextView selectedRange].location;
NSString *string = [myTextView string];

[string enumerateSubstringsInRange:(NSRange){ 0, [string length] } options:NSStringEnumerationByWords usingBlock:^(NSString *word, NSRange wordRange, NSRange enclosingRange, BOOL *stop) {
if (NSLocationInRange(insertionPoint, wordRange)) {
    NSTextStorage *textStorage = [myTextView textStorage];
    NSDictionary *attributes = @{ NSForegroundColorAttributeName: [NSColor redColor] }; // e.g.
    [textStorage addAttributes:attributes range:wordRange];
    *stop = YES;
}}];
Run Code Online (Sandbox Code Playgroud)

  • 要检查光标位置的变化,您应该观察"NSTextViewDidChangeSelectionNotification"通知,并检查以确保新选定范围的长度为0. (2认同)