0

I'm trying to detect if the U key is pressed or not, and if it is it should print("BUT...BUT.."); but I'm not sure how to check for different keys, as the documentation for key presses is quite bad.. I found an answer with keycodes but they only work for QWERTY keyboards

viewcontroller.swift

override func viewDidLoad(){
    super.viewDidLoad();
    let f = Foo();
    f.doSonethimg();
}

override func keyDown(theEvent: NSEvent){
    let f = Foo();
    f.KeyDown(theEvent);
}

Foo.swift

public func doSonething(){
    print("Hello from Dylib");
}

public func keyDown(event: NSEvent){
        if let keyString = theEvent.charactersIgnoringModifiers where keyString == "u" || keyString == "U" {
    Swift.print("BUT...BUT…")
}
}

How would I change the keyDown Function to respond to U and what is it's default key?

I've looked at - Detecting key press event in Swift and https://superuser.com/questions/399430/mouse-button-and-keypress-counter-for-mac-os-x

also see - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/EventOverview/HandlingKeyEvents/HandlingKeyEvents.html - Overriding the keyDown: Method

Community
  • 1
  • 1
Gerwin
  • 1,572
  • 5
  • 23
  • 51
  • 1
    Consider that the behavior of the function keys (as F-keys) depends on a setting in System Preferences – vadian Apr 28 '16 at 10:20
  • that's true, thank you i'll update my question accordingly – Gerwin Apr 28 '16 at 10:28
  • 1
    Did you read the documentation of NSEvent? NSEvent has methods for Getting Key Event Information, like `characters`. Keydown events don't have a default key. – Willeke Apr 28 '16 at 12:48

1 Answers1

5

You can easily check for a character by using NSEvents charactersIgnoringModifiers property.

func keyDown(theEvent: NSEvent) {
    if let keyString = theEvent.charactersIgnoringModifiers where keyString == "u" || keyString == "U" {
        Swift.print("BUT...BUT…")
    }
}

Note: There is a difference between checking for 'u' and 'U'. They are modified by Shift. So if you want to have both recognized, check for both. (as in the example above)

Responder Chain:
The keyDown function is only called when the view or viewController participates in the so called Responder Chain.

To set up your viewController for being part of the Responder Chain, read the following documentation.

mangerlahn
  • 4,746
  • 2
  • 26
  • 50
  • 1
    The keyDown event in my viewcontroller is never called so it won't enter the if do you know why this is? – Gerwin Apr 29 '16 at 07:19