ios - 子类化 UIView 时如何检测箭头键?
问题描述
基本上,当按下其中一个箭头键时,我想做一些事情。
我读过很多不同的问题。他们中的许多人都在谈论keyDown
,但那是为了NSViewController
或NSWindow
(这个和这个(Apple Documention))。当我使用这个时,我以为我正在做某事:
func setKeys() {
let up = UIKeyCommand(input: UIKeyCommand.inputUpArrow, modifierFlags: [], action: #selector(upPressed))
}
@objc func upPressed() {
print("Hello")
}
但是,upPressed()
甚至没有调用。实现这一目标的最佳方法是什么?
解决方案
您没有使用返回的 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")
}
}
推荐阅读
- django - 获取保存在 django bulk_create 中的记录总数
- reactjs - 创建新的反应应用程序时如何停止权限
- python - Django:更新帖子后,我怎样才能使“更新”成功消息暂时,直到我刷新页面。因为现在刷新后它仍然存在
- github - 通过 Github 发布网站时出现“找不到页面”错误
- python - 带有用户输入的 FizzBuzz 类型游戏 - 整数错误
- python - Python - BeautifulSoup 不会产生相同的代码
- python - 在 Python 中填充具有不同名称的列
- r - 尝试使用 ranger 插入插入符号时出错
- python - await 不返回具有线程中设置的值的未来值
- javascript - 无法在 useEffect 挂钩中测试超时功能