Key Press (Recognition) in Swift 2.0

Is there a way to have Swift 2 recognize you are pressing the up arrow, down arrow, left arrow, and right arrow without having to use "Apple key codes" (if you Google that phrase it is the first hit) so here is a working code, but I would like to not have to use numbers to identify each key:


override func keyDown(keyEvent: NSEvent) {

/

let code = keyEvent.keyCode

if code == 126{

for ball in ballArray{

ball.physicsBody?.applyForce(CGVector(dx: 0, dy: 1000))

}

}

if code == 125{

for ball in ballArray{

ball.physicsBody?.applyForce(CGVector(dx: 0, dy: -1000))

}

}

if code == 124{

for ball in ballArray{

ball.physicsBody?.applyForce(CGVector(dx: 1000, dy: 0))

}

}

if code == 123{

for ball in ballArray{

ball.physicsBody?.applyForce(CGVector(dx: -1000, dy: 0))


}

}

if code == 49{

for ball in ballArray{

ball.removeFromParent()

}

ballArray = Array<SKSpriteNode>()

}


}


I was hoping to also find a way for the spacebar to be used without having to use the arbitrary key codes.

Accepted Reply

There is no defined list of keycodes.

The traditional reference for virtual keycodes was Inside Macintosh: V-190. A few years back we added symbolic constants to the macOS SDK (see

kVK_ANSI_A
and friends in
<HIToolbox/Events.h>
). You can access these from Swift just fine, you just need an
import Carbon.HIToolbox.Events
.

OTOH, is is hardly a Swift-friendly interface, so feel free to file a bug requesting something better. Please post your bug number, just for the record.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Replies

There is no defined list of keycodes.


But you can call interpretKeyEvents: in keyDown: which will call appropriate action methods, all of which are documented in NSResponder (e.g. moveLeft:, insertTab:, etc.)

have a look here :

http : / / stackoverflow.com/questions/2080312/where-can-i-find-a-list-of-key-codes-for-use-with-cocoas-nsevent-class

There is no defined list of keycodes.

The traditional reference for virtual keycodes was Inside Macintosh: V-190. A few years back we added symbolic constants to the macOS SDK (see

kVK_ANSI_A
and friends in
<HIToolbox/Events.h>
). You can access these from Swift just fine, you just need an
import Carbon.HIToolbox.Events
.

OTOH, is is hardly a Swift-friendly interface, so feel free to file a bug requesting something better. Please post your bug number, just for the record.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"