I have an NSSearchField
inside a NSToolbar
that I am attempting to set makeFirstResponder
on but it is working intermittently. At times the NSSearchField
will become the first responder without the call to makeFirstResponder
and makeFirstResponder
is returning true
as if it were set successfully. Setting NSWindow.initialFirstResponder
has also failed to work.
class ViewController: NSViewController {
override func viewDidAppear() {
super.viewDidAppear()
view.window?.makeFirstResponder(view.window?.windowController?.searchField
}
}
I have had consistent working results by delaying the code with a timer but this is a less than ideal solution.
class ViewController: NSViewController {
override func viewDidAppear() {
super.viewDidAppear()
Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { _ in
self.view.window?.makeFirstResponder(self.windowController?.searchField)
}
}
}
I found a blog that led me to find the reason why this was happening. By default in macOS an NSWindow has an isRestorable Boolean value that will recall whatever the last firstResponder
was regardless of what is set as an initialFirstResponder
or what is set inside viewDidAppear
, etc.