NSTextFinder sets the search bar and transparent visual feedback programmatically

I have an NSTextView that uses a search bar ( [textView setUsesFindBar:YES]; ).

I have 2 questions.

  • How to clear visual feedback from a search operation?

    My problem arises when I programmatically change the contents of a text field. The visual feedback for the search operation on the previous content remains after the content has been changed. Obviously, these yellow fields do not apply to new content, so I need to clear them when changing the contents of a textView.

    Note. I did not implement the NSTextFinderClient protocol because I have a simple text element and the search bar works without any other effort.

  • How to send a search bar to the search bar?

+4
source share
1 answer

I found the answers, so for others here is how to do it.

First you need an instance of NSTextFinder so you can control it. We set this in code.

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

First answer . To clear visual feedback, I can do one of two things. I can just cancel the visual feedback ...

 [textFinder cancelFindIndicator]; 

Or I can warn NSTextFinder that I am going to change my textView content ...

 [textFinder noteClientStringWillChange]; 

Second answer : there is a global NSFindPboard. You can use this to search.

 // 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 

There is a problem though. The actual text field in the search bar is not updated after this code. I found that if I switch the first responder, I can update it ...

 [myWindow makeFirstResponder:outlineView]; [myWindow makeFirstResponder:textView]; 
+11
source

All Articles