检查是否按了u键Swift Cocoa [英] Check if the u key is pressed Swift Cocoa
问题描述
我正在尝试检测是否按下了U
键,是否应该按print("BUT...BUT..");
键,但是我不确定如何检查不同的键,因为有关按键的文档非常多不好.我找到了键码的答案,但它们仅适用于QWERTY键盘
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…")
}
}
如何更改keyDown
函数以响应U
,它的默认键是什么?
How would I change the keyDown
Function to respond to U
and what is it's default key?
我查看了-在Swift中检测按键事件, https://superuser.com/questions/399430/mouse-针对Mac OS X的按钮和按键计数器
另请参阅- https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/EventOverview/HandlingKeyEvents/HandlingKeyEvents.html -覆盖keyDown:方法
also see - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/EventOverview/HandlingKeyEvents/HandlingKeyEvents.html - Overriding the keyDown: Method
推荐答案
您可以使用NSEvent
的charactersIgnoringModifiers
属性轻松地检查字符.
You can easily check for a character by using NSEvent
s charactersIgnoringModifiers
property.
func keyDown(theEvent: NSEvent) {
if let keyString = theEvent.charactersIgnoringModifiers where keyString == "u" || keyString == "U" {
Swift.print("BUT...BUT…")
}
}
注意:检查"u"和"U"之间是有区别的.它们通过 Shift 进行了修改.因此,如果您想同时识别两者,请检查两者. (如上例所示)
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)
响应链:
仅当view或viewController参与所谓的响应者链.
Responder Chain:
The keyDown function is only called when the view or viewController participates in the so called Responder Chain.
要将您的viewController设置为响应者链的一部分,请阅读以下
To set up your viewController for being part of the Responder Chain, read the following documentation.
这篇关于检查是否按了u键Swift Cocoa的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!