3
votes

I have a view that contains an NSTableView and an NSTextField. The table view has focus. I would like to use the text field as a filter for the table view. Is there any way that I can send a key press event, which is captured by the table view, to the NSTextField?

Here is the keyDown func as I have it, I would like to send theEvent to the text field in the default handler of the switch statement.

override func keyDown(theEvent: NSEvent) {
    let s   =   theEvent.charactersIgnoringModifiers!
    let s1  =   s.unicodeScalars
    let s2  =   s1[s1.startIndex].value
    let s3  =   Int(s2)
    switch s3 {
        case NSUpArrowFunctionKey:
            self.previous()
            return
        case NSDownArrowFunctionKey:
            self.next()
            return
        default:
            // this appends the text to the textField, Is there a way to send theEvent to the textField?
            textField.stringValue = textField.stringValue + s;

            // textField.keyDown(theEvent) // this does not work
            break
    }
}

I would like to not have to force the user to change focus to the text field in order to filter the table view results.

1
Text fields do not process key events. When they have focus, a separate text view is added to the window that overlaps the text field. That text view, known as the field editor, processes key events and other things (e.g. Edit menu items). The text field does not. So, when a text field does not have focus, there's nothing to handle such events. The Mac UI convention is to use a separate NSSearchField and do type-to-select in the table.Ken Thomases
Thanks for explaining this. I decided to leave the NSTextField as the firstResponder and handle the events I wanted in the NSTextFieldDelegate control function using doCommandBySelector.Euan M

1 Answers

1
votes

As far as I understand it the -keyDown: is sent to the firstResponder which in this case is the table view.

I don't like this idea and I would implement this is a different way, but you could try inserting the text field into the responder chain and a position above table view. You would have to subclass the text field and implement mouseDown to capture the events and you would also have to change you table views mouse down implementation so it didn't capture the event for the text field. This is overly complicated.

Why not simply set the target/action of the text field and deal with user input outside of the event loop?