2012-12-12 36 views
4

我有一個使用查找欄([textView setUsesFindBar:YES];)的NSTextViewNSTextFinder設置搜索字符串並以編程方式清除視覺反饋

我有2個問題。

  1. 如何清除查找操作中的視覺反饋?

    當我以編程方式更改textView的內容時,會出現問題。內容更改後,對先前內容的搜索操作的視覺反饋仍然存在。很顯然,這些黃色框不適用於新內容,所以我需要一種方法來在更改textView內容時清除它們。

    注:我沒有實現NSTextFinderClient協議,因爲我有一個簡單的textView和查找欄只是沒有任何其他努力的工作。

  2. 如何將搜索字符串發送到查找欄?

回答

11

我找到了我的答案,所以對於其他人來說,這裏是如何做到的。

首先你需要一個NSTextFinder的實例,以便你可以控制它。我們用代碼來設置它。

textFinder = [[NSTextFinder alloc] init]; 
[textFinder setClient:textView]; 
[textFinder setFindBarContainer:[textView enclosingScrollView]]; 
[textView setUsesFindBar:YES]; 
[textView setIncrementalSearchingEnabled:YES]; 

第一個答案:要清除視覺反饋,我可以做的兩件事情無論是。我可以取消視覺反饋...

[textFinder cancelFindIndicator]; 

或者,我可以提醒NSTextFinder說我要改變我的TextView的內容...

[textFinder noteClientStringWillChange]; 

第二個答案:有全球NSFindPboard。您可以使用它來設置搜索。

// change the NSFindPboard NSPasteboardTypeString 
NSPasteboard* pBoard = [NSPasteboard pasteboardWithName:NSFindPboard]; 
[pBoard declareTypes:[NSArray arrayWithObjects:NSPasteboardTypeString, NSPasteboardTypeTextFinderOptions, nil] owner:nil]; 
[pBoard setString:@"new search" forType:NSStringPboardType]; 
NSDictionary* options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSTextFinderCaseInsensitiveKey, [NSNumber numberWithInteger:NSTextFinderMatchingTypeContains], NSTextFinderMatchingTypeKey, nil]; 
[pBoard setPropertyList:options forType:NSPasteboardTypeTextFinderOptions]; 

// put the new search string in the find bar 
[textFinder cancelFindIndicator]; 
[textFinder performAction:NSTextFinderActionSetSearchString]; 
[textFinder performAction:NSTextFinderActionShowFindInterface]; // make sure the find bar is showing 

雖然存在問題。該代碼後,查找欄中的實際文本字段不會更新。我發現,如果我切換第一響應者,那麼我可以讓它更新...

[myWindow makeFirstResponder:outlineView]; 
[myWindow makeFirstResponder:textView];