Select next NSTextField with Tab key in Swift

Viewed 4990

Is there a way to change the responder or select another text view by pressing tab on the keyboard, in Swift?

enter image description here

Notes: It's for a fill in the blank type application.

My VC creates a list of Words [Word], and each of those words has its own WordView - word.wordView. The WordView is what is displayed. WordView is a child of NSTextView.

I tried to override keydown but it doesn't allow me to type anything in the text view.

4 Answers

If you want some control over how your field tabs or moves with arrow keys between fields in Swift, you can add this to your delegate along with some move meaningful code to do the actual moving like move next by finding the control on the superview visibly displayed below or just to the right of the control and can accept focus.

 public func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
        switch commandSelector {
        case #selector(NSResponder.insertTab(_:)), #selector(NSResponder.moveDown(_:)):
            // Move to the next field
            Swift.print("Move next")
            return true
        case #selector(NSResponder.moveUp(_:)):
            // Move to the previous field
            Swift.print("Move previous")
            return true
        default:
            return false
        }
        return false // I didn't do anything
    }

I had the same or a similar problem, in that I wanted to use an NSTextView field, to allow multiple lines of text to be entered, but it was the sort of field where entering a tab character would make no sense. I found an easy fix for this: NSTextView has an instance property of isFieldEditor, which is set to false by default; simply set this to true, and tabs will now skip to the next field.

Related