Search code examples
objective-ceventsnsviewkeydownnsviewcontroller

NSView doesn’t catch keyDown events


I need to catch mouseDown and keyDown events in a subclass of NSViewController and as it’s not possible (please, correct me if I’m wrong) I left my GameViewController class blank and put all it’s methods to a new GameView class. In the identity inspector of GameViewController.xib I set my class to GameView while File’s Owner is set to GameViewController. After all, my mouseDown method works, but keyDown doesn’t. I tried this:

- (BOOL) acceptsFirstResponder {
    return YES;
}

but it didn’t help.

Please, show me what to do.

UPD: Actually keyDown method works, but first I need to click somewhere on the blank space of my window and only then everything works as it was planned. Once again, mouseDown events are triggered with no problems. What may I be doing wrong?


Solution

  • Your view accepts first responder when offered it, but nothing is attempting to make it the first responder until you click.

    Set the window's initialFirstResponder some time before showing it. If you're using a NIB, it can be set there. Or you could do it programmatically.

    After the window is shown, you can call [window makeFirstResponder:view] to make the view the first responder of its window.