【问题标题】:Get & Highlight Current Word in an NSTextView在 NSTextView 中获取并突出显示当前单词
【发布时间】:2012-09-24 03:12:07
【问题描述】:

好的,这就是我想要的:

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

我不知道该怎么做:我的意思是我主要关心的是在NSTextView 中获得当前位置并在点得到这个词(我知道一些文本插件支持这一点,但我不是确保在最初的NSTextView 实现中......)

是否有任何内置功能?或者,如果没有,有什么想法吗?


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

NSInteger insertionPoint = [[[myTextView selectedRanges] objectAtIndex:0] rangeValue].location;

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

【问题讨论】:

  • 我真的很好奇为什么这个问题得到了'-1'。无法理解/回答一个人的问题并不足以成为拒绝它的理由。或者至少评论会更有建设性......嗯?
  • 我也不知道为什么。我要平衡一下。
  • 这其实是个好问题。 +1。

标签: objective-c cocoa nstextview


【解决方案1】:

这是一种方法:

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

【讨论】:

  • 哦,我没有做突出显示。追加…
  • 非常感谢。 很好的答案。 (我冒昧地纠正了一两个不起作用的小位)。现在再给你一个:知道如何将选择器连接到光标位置更改时触发的NSTextView 吗? (使用键盘或鼠标)。我应该使用某种观察者吗?
  • 我正要发帖说我没有测试它,但后来我分心了。
  • 哦,我们都知道忽略括号或类似的东西是多么容易......不用担心! ;-)
  • 要检查光标位置的变化,您应该观察NSTextViewDidChangeSelectionNotification 通知,并检查以确保新选定范围的长度为0。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2014-10-03
    • 1970-01-01
    • 2013-06-29
    • 2011-12-20
    • 2012-09-10
    • 2021-04-07
    • 2014-09-12
    • 2015-12-06
    • 2014-08-07
    相关资源
    最近更新 更多