Euan M
Euan M

Reputation: 66

How to send a key event to an NSTextField that does not have focus in swift

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.

Upvotes: 3

Views: 1284

Answers (1)

Daniel Farrell
Daniel Farrell

Reputation: 9740

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?

Upvotes: 1

Related Questions