Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTextFinder set search string and clear visual feedback programmatically

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

I have 2 questions.

  1. How do I clear the visual feedback from a find operation?

    My problem happens when I programmatically change the content of the textView. The visual feedback for a search operation on the previous content remains after the content change. Obviously these yellow boxes do not apply to the new content so I need a way to clear them when changing the textView content.

    Note: I did not implement the NSTextFinderClient protocol because I have a simple textView and the find bar just works without any other effort.

  2. How can I send a search string to the find bar?

like image 236
regulus6633 Avatar asked Dec 12 '12 11:12

regulus6633


1 Answers

I found my answers, so for others here's how to do it.

First you need an instance of NSTextFinder so you can control it. We set that up 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 either of 2 things. I can just cancel the visual feedback...

[textFinder cancelFindIndicator];

Or I can alert NSTextFinder that I'm about to change my textView content...

[textFinder noteClientStringWillChange];

Second answer: There's a global NSFindPboard. You can use that to set a 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's a problem though. The actual text field in the find bar does not get updated after that code. I found that if I toggle the first responder then I can get it to update...

[myWindow makeFirstResponder:outlineView];
[myWindow makeFirstResponder:textView];
like image 200
regulus6633 Avatar answered Oct 02 '22 15:10

regulus6633