Reputation: 3108
I have the code all done for my keydown actions, but i dont know what to do with the first responder that every site i go to seems to skim over. Can anyone tell me how to set it up to recognise keydown actions in cocoa objectivec?
Thanks
Upvotes: 2
Views: 2484
Reputation: 397
Here is what I've done and it works well. (Swift 3 for macOS Sierra)
override func viewDidLoad() {
keyIsDown = false // variable defined in the NSViewController
NSEvent.addLocalMonitorForEvents(matching: .keyUp) { (aEvent) -> NSEvent? in
self.keyUp(with: aEvent)
return aEvent
}
NSEvent.addLocalMonitorForEvents(matching: .keyDown) { (aEvent) -> NSEvent? in
self.keyDown(with: aEvent)
return aEvent
}
}
Now I also override these:
override var acceptsFirstResponder: Bool { return true }
override func becomeFirstResponder() -> Bool { return true }
override func resignFirstResponder() -> Bool { return true }
And these:
override func keyUp(with event: NSEvent) {
keyIsDown = false
if event.keyCode == 1 {
print("s key released")
}
}
override func keyDown(with event: NSEvent) {
if keyIsDown == true {
return
}
keyIsDown = true
// Whatever you'd like to do (check to see which key released, etc.)
}
That should get you started.
Upvotes: 0
Reputation: 96323
First, keyDown:
is an event message, not an action message. Note that its argument is an NSEvent, not a UI object of some sort (such as an NSControl or NSMenuItem).
Action messages go down the responder chain, in which case the “first responder” is not special. Each responder will hand any action message it doesn't know how to handle off to its next responder. This is the “responder chain”. The first responder is simply whatever responder is at the head of the responder chain—i.e., is first. You would simply need to be in that chain, behind anything that doesn't know how to respond to the action being passed down it.
But since this is an event message, things are different. You need to be the key view, which is the first responder.
And that's all there is to it. You need to respond to the keyDown:
message (and possibly related ones) in a view, and that view needs to be the first responder to receive the message.
The NSResponder class reference and Cocoa Event-Handling Guide will tell you more.
Upvotes: 4