Pressing the tab key to switch from one text field to another

Personally, when I use a macOS application, I often use the tab key to switch from one text field to another. Meanwhile, I've been developing macOS applications for 10 years or so. Sometimes, if I press the tab key, my application won't switch from one text field to another. I wonder why that happens? I'm working on a new desktop application now. It's almost done. And pressing the tab key won't let me switch from one text field to another. Does anybody have any idea why? Thanks.

Accepted Reply

Tab moves to next NSResponder.


You can force an order:

Have a look here for details.

https://stackoverflow.com/questions/36000867/select-next-nstextview-with-tab-key-in-swift


I tested and noticed a few points:

- could not make it work by defining nextKeyView in IB, I had to do it in code

- in code, don't implement in viewDidLoad, but viewDidAppear

    override func viewDidAppear() {
        firstTextField.nextKeyView = secondTextField
        secondTextField.nextKeyView = thirdTextField
        thirdTextField.nextKeyView = firstTextField
    }

- of course make sure to set the delegate for the textFields (that can be done in IB)

- and don't forget to dclare the ViewController as conforming to NSTextFieldDelegate

Replies

Tab moves to next NSResponder.


You can force an order:

Have a look here for details.

https://stackoverflow.com/questions/36000867/select-next-nstextview-with-tab-key-in-swift


I tested and noticed a few points:

- could not make it work by defining nextKeyView in IB, I had to do it in code

- in code, don't implement in viewDidLoad, but viewDidAppear

    override func viewDidAppear() {
        firstTextField.nextKeyView = secondTextField
        secondTextField.nextKeyView = thirdTextField
        thirdTextField.nextKeyView = firstTextField
    }

- of course make sure to set the delegate for the textFields (that can be done in IB)

- and don't forget to dclare the ViewController as conforming to NSTextFieldDelegate

You need to arrange for the key view loop to be set up. Each view has

nextKeyView
and
previousKeyView
properties. You can set those manually in IB or programmatically to form a chain through your window's views, but it's usually easiest to let the window manage it. For that, make sure that the window's
autorecalculatesKeyViewLoop
property is set to true.

That's excellent. Yes, it works. Thanks a lot.