user4064541
user4064541

Reputation:

Swift OSX key event

I have been working on a Cocoa OSX project in swift that requires the use of keyboard input to preform an action. On keydown i want to move an object across the window, but stop the object as soon as the key is let up. I have looked in the documentation for AppKit and found the KeyDown function but I cannot seem to figure out how to use it. I want to create a function to call in my game update timer that will preform this. Thanks

import Cocoa
import Appkit

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

@IBOutlet weak var window: NSWindow!

func applicationDidFinishLaunching(aNotification: NSNotification) {
    // Insert code here to initialize your application

     func keyDown(theEvent: NSEvent) {
        if (theEvent.keyCode == 1){
            println("test")
        }

    }

}

func applicationWillTerminate(aNotification: NSNotification) {
    // Insert code here to tear down your application



}

}

Upvotes: 11

Views: 16828

Answers (3)

twohyjr
twohyjr

Reputation: 120

SWIFT 4: I created a repo solving this problem on my games. I mainly use this with my MTKView but should work with NSViews too.

https://github.com/twohyjr/NSView-Keyboard-and-Mouse-Input

Upvotes: 2

cleme001
cleme001

Reputation: 341

 override func keyDown(with event: NSEvent) {
    if (event.keyCode == 1){
        //do whatever when the s key is pressed
        print("S key pressed")
    }
}

Updated for SWIFT 3

Upvotes: 5

Kendel
Kendel

Reputation: 1708

Here is some example code:

  override func keyDown(theEvent: NSEvent) {
            if (theEvent.keyCode == 1){
           //do whatever when the s key is pressed
        } 

    }

Key codes: enter image description here

Upvotes: 25

Related Questions