Reputation: 119144
I have a simple cocoa user interface with a list of items and a search field, implemented using NSTableView and NSSearchField, respectively. The data source and all of the bindings are set up and working nicely. I see my data in the list, and I can search through it by typing strings in the search field. As I type in more text, the number of items in the list gets smaller and smaller, eventually reduced to the one item I was searching for.
Now, how can I clear the text in the search field and force the list to go back to normal? I can make this happen by clearing the text manually (using the keyboard), but when I try to do it programmatically, the hidden items in the list do not come back.
I'm using this:
[searchField setStringValue:@""];
to clear the text in the search field, but it does not reset the list.
Any ideas? Is there a simple [searchField reset] method that I just can't find in the documentation?
Upvotes: 8
Views: 2652
Reputation: 3476
Pressing return after typing in some text will call searchFieldDidStartSearching, followed by searchFieldDidEndSearching and clear out the textField.
extension NSSearchField {
func resetSearch() {
if let searchFieldCell = self.cell as? NSSearchFieldCell {
searchFieldCell.cancelButtonCell?.performClick(self)
}
}
}
Here is my delegate code
extension ViewController : NSSearchFieldDelegate {
func searchFieldDidEndSearching(_ sender: NSSearchField) {
print("end \(sender.stringValue)")
}
func searchFieldDidStartSearching(_ sender: NSSearchField) {
print("start \(sender.stringValue)")
DispatchQueue.main.async {
// calling resetSearch on main thread preserves focus ring
sender.resetSearch()
}
}
}
Upvotes: 0
Reputation: 6308
[[[searchField cell] cancelButtonCell] performClick:self];
might work, but it really seems like there should be a "proper" solution. Is your table view actually bound to the searchField's value, or is it bound to some intermediate object that is not getting updated when you set the searchField's contents to the empty string programatically (but which is getting updated when you type because of the way the bindings are set up in the nib)?
Upvotes: 4
Reputation: 1573
I figured it out. The following code works:
[searchField setStringValue:@""]; [[[searchField cell] cancelButtonCell] performClick:self];
Upvotes: 9
Reputation: 119144
I figured it out. The following code works:
[searchField setStringValue:@""];
[[[searchField cell] cancelButtonCell] performClick:self];
Upvotes: 7