I want use keyDown method to see which key pressed in keyboard but it does not work also my computer makes sounds to tell the key even does not work.
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func keyDown(with event: NSEvent) {
print(event)
}
}
CodePudding user response:
Only the responders in the current responder chain get a shot at handling events like key events, and then only if some other responder in the chain doesn't handle it first. So, you'll need to make sure that your view controller is managing a view that's the keyboard focus when the event actually takes place, and that the focused view doesn't handle the event itself.
CodePudding user response:
Some view in your view controller's view graph needs to be the first responder to make this work. You need to make a custom class for the view, and then add this in the view:
override var acceptsFirstResponder: Bool {
true
}
If you have something like a text field that gets keyboard focus then this probably isn't necessary, but a plain NSView
on its own doesn't become first responder.
Since you have found my descriptions of the code to be inadequate, here's the entire thing. The view controller code looks like this:
class ViewController: NSViewController {
override func keyDown(with event: NSEvent) {
print("\(event)")
}
}
The custom view code looks like this:
class MyView: NSView {
override var acceptsFirstResponder: Bool {
true
}
}
Also, as I described, I made the view an instance of my custom view:
That is all of the code in the app. There is no more. The keyDown
function works as expected.