1

I need to change behavior of input fields in a really simple app: Simple OSX app

Whenever i launch the application the first text field get the focus, but i don't want this behavior.

I tried checking "Refuses first responder" in IB. It works but with this option checked i can't move between input fields pressing "tab" button.

What can i do to avoid focus at startup and keep the ability to move with tab keyboard button ?

MatterGoal
  • 16,038
  • 19
  • 109
  • 186

4 Answers4

3

The (previously) accepted answer isn't reliable and doesn't work very well. The other answer with the hidden NSTextField isn't very great either because now you have a new element in your Tab order.

The solution I've found works best so far is:

Make the NSTextField refusesFirstResponder YES on app launch.

Then, in viewDidAppear for the controller, go ahead and set refusesFirstResponder back to NO.

Everything behaves perfect after launch, and I don't have a greedy NSTextField stealing first responder on app startup.

MarcWan
  • 2,943
  • 3
  • 28
  • 41
1

I found the solution, you can add [window makeFirstResponder:nil]; after awakeFromNib for example in applicationDidfinishLaunching.

MatterGoal
  • 16,038
  • 19
  • 109
  • 186
0

window?.makeFirstResponder(nil) does not work for me - when I check who is the first responder, it is the window (and not a NSTextField) but still, the first NSTextField is selected and active. The solution for me (though I know not the cleanest one) was to create a hidden text field and make it the first responder every time the window did load.

window?.makeFirstResponder(nil) worked only when I set all NSTextFields to RefuseFirstResponder, but then using Tab to switch between them of course do not work.

Robert
  • 5,278
  • 43
  • 65
  • 115
0

This worked for me,

override func viewDidAppear() {

Timer.scheduledTimer(withTimeInterval: 0.1, repeats: false) { [weak self] (timer) in
            NSApplication.shared.windows[0].makeFirstResponder(self?.textUsername)
            let tRange = self?.textUsername.currentEditor()?.selectedRange
            self?.textUsername.currentEditor()?.selectedRange = NSMakeRange((tRange?.length)!, 0)
        }
}
Faris Muhammed
  • 970
  • 13
  • 17