子类化 UIView 时如何检测箭头键?

How to detect arrow keys when subclassing a UIView?

基本上,我想在按下其中一个箭头键时执行某些操作。

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

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

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

然而,upPressed() 甚至没有被调用。实现此目标的最佳方法是什么?

您没有使用 returned UIKeyCommand 实例 up

苹果:"After creating a key command object, you can add it to a view controller using the addKeyCommand: method of the view controller. You can also override any responder class and return the key command directly from the responder’s keyCommands property."

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")
    }

}