2012-09-23 35 views
6

好了,這就是我想要的:(?作爲NSRange獲取並突出顯示當前字在NSTextView

  • 我們有一個NSTextView
  • 獲取「當前」字,在光標位置(如何可以這樣來確定)
  • 選中它(更改其屬性)

我不知道如何去了解這一點:?我的意思是我的主要關注的是讓內NSTextView並獲取當前位置在點字(我知道一些文本的插件支持,但我不知道作爲原始NSTextView執行...)

是否有任何內置的功能是什麼?或者,如果沒有,有什麼想法?


UPDATE:光標位置(解決)

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

現在,仍然試圖找到一個指定的基本字一個解決辦法...

+1

我真的很好奇,爲什麼這個問題得到了「-1」。不能理解/回答某個人的問題不足以成爲降低它的原因。或者至少有一條評論會更有建設性......嗯? –

+1

我不知道爲什麼,要麼。我要平衡它。 – Wevah

+1

這實際上是一個很好的問題。 +1。 – 2012-09-23 18:20:33

回答

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

哦,我沒有做突出顯示。正在追加... – Wevah

+0

非常感謝。 **很好的答案**。 (我冒昧地糾正了一兩個不起作用的小片段)。現在又一個給你:任何想法如何將選擇器連接到當光標位置改變時觸發的'NSTextView'? (使用鍵盤或鼠標)。我應該使用某種觀察者嗎? –

+0

我打算髮布我沒有測試它,但後來我分心。 – Wevah

1

簡單的算法來找到這個詞的界限(假設這個詞是空間分辯的):

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

非常感謝。 :-) –

+0

@ Dr.Kameleon沒問題:) – 2012-09-23 19:30:08