【发布时间】:2015-11-23 07:23:55
【问题描述】:
在 iOS 8.4 上的 Swift 2 中,我如何检测蓝牙键盘的 Up、Down 或 Space 条键何时被按下,以便我可以做出响应?
示例代码会很有帮助。
【问题讨论】:
在 iOS 8.4 上的 Swift 2 中,我如何检测蓝牙键盘的 Up、Down 或 Space 条键何时被按下,以便我可以做出响应?
示例代码会很有帮助。
【问题讨论】:
对不起,我来晚了,我才意识到我可以帮助你。
你需要使用的是 UIKeyCommand。看看这个:http://nshipster.com/uikeycommand/
请注意,要检测箭头键按下,您需要 input: UIKeyInputLeftArrow 而不是 input: "j"(或等效项)。您还希望没有修饰符(因此用户不必按 CMD 向左箭头):请参阅 Key Commands with no modifier flags—Swift 2。
基本上,在您的 viewdidload 之后(外部)您会想要类似的东西:
override func canBecomeFirstResponder() -> Bool {
return true
}
override var keyCommands: [UIKeyCommand]? {
return [
UIKeyCommand(input: UIKeyInputDownArrow, modifierFlags: [], action: "DownArrowPress:"),
UIKeyCommand(input: UIKeyInputUpArrow, modifierFlags: [], action: "UpArrowPress:"),
UIKeyCommand(input: " ", modifierFlags: [], action: "SpaceKeyPress:")]
}
// ...
func DownArrowPress(sender: UIKeyCommand) {
// this happens when you press the down arrow.
}
func UpArrowPress(sender: UIKeyCommand) {
// this happens when you press the up arrow.
}
func SpaceKeyPress(sender: UIKeyCommand) {
// this happens when you press the space key.
}
我希望这会有所帮助,如果您需要更多帮助或有什么不对劲的地方,请回复 @owlswipe。
【讨论】:
UIKeyCommand 与input: " " 一起应用,但按下空格键时不会调用该操作。它适用于其他键,例如返回键:input: "\r" (Swift 5)
owlswipe 的 answer 为我工作,但是,我必须对 Swift 5 进行以下更改:
@objc func DownArrowPress(sender: UIKeyCommand) {
print("DOWNARROWPRESS")
}
@objc func UpArrowPress(sender: UIKeyCommand) {
print("UPARROWPRESS")
}
override var keyCommands: [UIKeyCommand]? {
return [
UIKeyCommand(input: UIKeyCommand.inputDownArrow, modifierFlags: [], action: #selector(DownArrowPress)),
UIKeyCommand(input: UIKeyCommand.inputUpArrow, modifierFlags: [], action: #selector(UpArrowPress))
]
}
【讨论】: