I have a search field (NSTextField
) called searchField
and when you type in it, it refreshes the data shown in a NSTableView
. The problem is that this refresh also triggers the selection of a table row, and that takes the focus out of the NSTextField
.
The user types in the search field:
func controlTextDidChange(_ obj: Notification) {
if let field = obj.object as? NSTextField, field == searchField{
refreshData()
}
}
Then the NSTableView
gets reloaded here:
func refreshData(){
//Process search term and filter data array
//...
//Restore previously selected row (if available)
let index = tableView.selectedRow
tableView.reloadData()
//Select the previously selected row
tableView.selectRowIndexes(NSIndexSet(index: index) as IndexSet, byExtendingSelection: false)
}
If I comment-out both the reloadData()
and the selectRowIndexes
then the search field behaves as intended (I can keep typing and it keeps the focus in the field). But if include either or both of those methods, the search field loses focus after I type the first character and refreshData()
is called.
How can I keep focus in my search field and not let the table reload hijack the focus?
Ugh... it turns out I could never get the
NSTableView
to let go of the focus because it wasn't set to allow an Empty selection state. Checking a box in Interface Builder fixed it.