I need to get the arrow keys pressed, but keyDown will not call (Swift)

I am trying to create a Mac application that displays images, and I want to go to the next image when I press the right arrow key. I looked through the entire stackoverflow stack and the internet, but just can't get it.

What I tried ... I tried to use keyDown(theEvent: NSEvent) , but it does not call when I press the keys. I believe this is because it is not in some kind of text area, but not sure.

What happens ... When I test the program, I press a key (with keyDown function ready for println("Key Pressed") ) and I get OS X rejection noise and do not print the console.

I heard about some NSView subclasses to override acceptsFirstResponder , but I'm new to the subclass, so any direction you could point me in would be great. Or if there is a way to do this without subclassing NSView, that would be great!

Thanks in advance! Sorry for the noobness.

+4
source share
1 answer

The subclass is less difficult than it seems.

Quick Guide:

General assumptions: keystrokes will be received in the subclass view of the NSViewController and will be processed in the view controller class

  • Create a new Cocoa class named MyView as a subclass of NSView
  • Replace the contents of the created class with

     import Cocoa let leftArrowKey = 123 let rightArrowKey = 124 protocol MyViewDelegate { func didPressLeftArrowKey() func didPressRightArrowKey() } class MyView: NSView { var delegate : MyViewDelegate? override func keyDown(event: NSEvent) { let character = Int(event.keyCode) switch character { case leftArrowKey, rightArrowKey: break default: super.keyDown(event) } } override func keyUp(event: NSEvent) { let character = Int(event.keyCode) switch character { case leftArrowKey: delegate?.didPressLeftArrowKey() case rightArrowKey: delegate?.didPressRightArrowKey() default: super.keyUp(event) } } override var acceptsFirstResponder : Bool { return true } } 
    • Change the ViewController view class in Interface Builder to MyView
    • In the ViewController class add the protocol MyViewDelegate - for example

       class ViewController: NSViewController, MyViewDelegate { 
    • In viewDidLoad() add

       let view = self.view as! MyView view.delegate = self self.nextResponder = view 
    • Implement the following delegate methods and add your code to switch the image (s)

       func didPressLeftArrowKey() { println("didPressLeftArrowKey") // process keystroke left arrow } func didPressRightArrowKey() { println("didPressRightArrowKey") // process keystroke right arrow } 

Delegate methods are called when you release the corresponding arrow keys.

+6
source

All Articles