2010-11-29 52 views
8

我試圖在NSTextView上編寫「高亮」功能。目前,一切都很好。您選擇一個文本範圍,該文本的背景顏色將變爲黃色。但是,它仍然被選中,背景是所選文字的標準藍色。如何在某些情況下使標準選擇指示器顏色不顯示?在NSTextView中更改文本選擇顏色

謝謝!

回答

16

使用-[NSTextView setSelectedTextAttributes:...]

例如:

[textView setSelectedTextAttributes: 
    [NSDictionary dictionaryWithObjectsAndKeys: 
     [NSColor blackColor], NSBackgroundColorAttributeName, 
     [NSColor whiteColor], NSForegroundColorAttributeName, 
     nil]]; 

你可以簡單地傳遞一個空的字典,如果你不希望在所有以任何方式表明的選擇(短躲在插入點)做。

另一種選擇是觀察選擇更改並使用temporary attributes應用「選擇」。請注意,臨時屬性用於顯示拼寫和語法錯誤並查找結果;所以如果您關心保留NSTextView的這些功能,那麼請確保只添加和刪除臨時屬性,而不能替換它們。

這樣的一個例子是(在NSTextView的子類):

- (void)setSelectedRanges:(NSArray *)ranges affinity:(NSSelectionAffinity)affinity stillSelecting:(BOOL)stillSelectingFlag; 
{ 
    NSArray *oldRanges = [self selectedRanges]; 
    for (NSValue *v in oldRanges) { 
     NSRange oldRange = [v rangeValue]; 
     if (oldRange.length > 0) 
      [[self layoutManager] removeTemporaryAttribute:NSBackgroundColorAttributeName forCharacterRange:oldRange]; 
    } 

    for (NSValue *v in ranges) { 
     NSRange range = [v rangeValue]; 
     if (range.length > 0) 
      [[self layoutManager] addTemporaryAttributes:[NSDictionary dictionaryWithObject:[NSColor blueColor] forKey:NSBackgroundColorAttributeName] 
             forCharacterRange:range]; 
    } 

    [super setSelectedRanges:ranges affinity:affinity stillSelecting:stillSelectingFlag]; 
} 
+0

與背景顏色設置爲clearColor,突出工作後,才全部選擇完成。如何在選擇正在進行時應用這些屬性? – DexterW 2010-11-29 06:34:36