Objective c 获取&;在NSTextView中高亮显示当前单词

Objective c 获取&;在NSTextView中高亮显示当前单词,objective-c,cocoa,nstextview,Objective C,Cocoa,Nstextview,好的,这就是我想要的: 我们有一个NSTextView 在光标位置获取“当前”字(作为NSRange?)(如何确定?) 高亮显示(更改其属性) 我不知道该怎么做:我的意思是,我主要关心的是在NSTextView中获得当前位置,并从某个角度获取单词(我知道一些文本插件支持这一点,但我不确定从最初的NSTextView实现开始…) 有内置的功能吗?或者,如果没有,有什么想法吗 更新:光标位置(已解决) 现在,仍在试图找到一种解决方法,用于指定基础单词…查找单词边界的简单算法(假设单词是空格分隔

好的,这就是我想要的:

  • 我们有一个
    NSTextView
  • 在光标位置获取“当前”字(作为
    NSRange
    ?)(如何确定?)
  • 高亮显示(更改其属性)
我不知道该怎么做:我的意思是,我主要关心的是在
NSTextView
中获得当前位置,并从某个角度获取单词(我知道一些文本插件支持这一点,但我不确定从最初的
NSTextView
实现开始…)

有内置的功能吗?或者,如果没有,有什么想法吗


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


现在,仍在试图找到一种解决方法,用于指定基础单词…

查找单词边界的简单算法(假设单词是空格分隔的):

这里有一个方法:

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;
}}];

我真的很好奇为什么这个问题有一个“-1”。不能理解/回答自己的问题不足以成为否决该问题的理由。或者至少一个评论会更有建设性。。。啊?我也不知道为什么。我要平衡一下,这是个好问题+1.噢,我没有做突出显示。附加…非常感谢。回答得很好。(我冒昧地纠正了一两个不起作用的小错误)。现在再给你一个:你知道当光标位置改变时,我如何将选择器连接到触发的
NSTextView
?(使用键盘或鼠标)。我应该使用一些观察者吗?我本来想发帖子说我没有测试它,但后来我分心了。哦,我们都知道忽略一个括号或类似的东西是多么容易。。。别担心!;-)要检查光标位置的更改,应观察
NSTextViewDidChangeSelectionNotification
通知,并检查以确保新选定范围的长度为0。
NSInteger prev = insertionPoint;
NSInteger next = insertionPoint;

while([[[myTextView textStorage] string] characterAtIndex:prev] != ' ')
    prev--;

prev++;

while([[[myTextView textStorage] string] characterAtIndex:next] != ' ')
    next++;

next--;

NSRange currentWordRange = NSMakeRange(prev, next - prev + 1);
NSString *currentWord = [[[myTextView textStorage] string] substringWithRange:currentWordRange];
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;
}}];