Swift KeyCommands 调用无效

记录一次swift开发中的坑.

做一个项目,需求是iPad pro外接键盘提供快捷键,于是查阅了资料, 发现几乎都是实现如该文所说就可以完成

http://UIKeyCommand - NSHipster 中文版

但是我照着做完却没有成功, 按键的action没有被调用, 在以下代码打断点, 发现每次按键确实会被调到改属性, 但是为什么里面selector keyPress没有被调用到呢?

override varkeyCommands: [UIKeyCommand]? {

  return [UIKeyCommand(input:"a", modifierFlags: .command, action:#selector(keyPress), discoverabilityTitle:"A")]

}

经过几次排查发现, 原来项目中有个判断菜单栏时忽略系统菜单栏的代码, 如下

override func canPerformAction(_action:Selector, withSender sender:Any?) ->Bool {

  if [#selector(changeStatus)].contains(action) {

    return true

  }

return false

}

所以在调用keycommads后代码来到canPerformAction, 里面没有把keyPress方法放进去, 所以无法被调用, 应该改为:

if [#selector(changeStatus), #selector(keyPress)].contains(action) {

  return true

}


以上.


更新于2017.8.31 04:47PM

突然发现一个好用的方法,不用去筛选selector, 而是用controller下的instancesRespond方法.这个方法是继承了NSObject的.

override func canPerformAction(_action:Selector, withSender sender:Any?) ->Bool {

    return YourController.instancesRespond(to: action)

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容