首页 > 解决方案 > 子类化 UIView 时如何检测箭头键?

问题描述

基本上,当按下其中一个箭头键时,我想做一些事情。

我读过很多不同的问题。他们中的许多人都在谈论keyDown,但那是为了NSViewControllerNSWindow这个这个(Apple Documention))。当我使用这个时,我以为我正在做某事:

func setKeys() {
    let up = UIKeyCommand(input: UIKeyCommand.inputUpArrow, modifierFlags: [], action: #selector(upPressed))
}

@objc func upPressed() {
    print("Hello")
}

但是,upPressed()甚至没有调用。实现这一目标的最佳方法是什么?

标签: iosswiftuiviewkeyboardsubclass

解决方案


您没有使用返回的 UIKeyCommand 实例up

Apple:“创建键盘命令对象后,您可以使用视图控制器的 addKeyCommand: 方法将其添加到视图控制器。您还可以覆盖任何响应者类并直接从响应者的 keyCommands 属性返回键盘命令。”

class Test: UIViewController{

   override func viewDidLoad() {
       super.viewDidLoad()
       setKeys()
   }

   func setKeys() {
      let up = UIKeyCommand(input: UIKeyCommand.inputUpArrow, modifierFlags: [], action: #selector(upPressed))
      self.addKeyCommand(up)
   }

   @objc func upPressed() {
      print("Hello")
   }
}



使用模拟器和硬件键盘对此进行了测试。

另外:如果您要直接通过 UIView 实现它,您必须这样做:“......您还可以覆盖任何响应者类并直接从响应者的 keyCommands 属性返回键命令。” 因为 UIView 符合 UIResponder

class CustomView: UIView{
    override var keyCommands: [UIKeyCommand]? {
       return  [UIKeyCommand(input: UIKeyCommand.inputUpArrow, modifierFlags: [], action: #selector(upPressed))]
    }

    @objc func upPressed(){
        print("hello world")
    }

}


推荐阅读