2

UIKeyCommand我在 Swift中遇到了问题。我有两个UIViewVontroller和。我正在使用此代码打开:ProjectsViewControllerViewControllerViewControllerProjectsViewController

let editor = self.storyboard?.instantiateViewController(withIdentifier: "editor")
self.present(editor!, animated: true, completion: nil)

在我的ProjectsViewController课上,我有一些UIKeyCommands

override var keyCommands: [UIKeyCommand]?
{
  if #available(iOS 9.0, *)
  {
    return [
      UIKeyCommand(input: "n", modifierFlags: .command, action: #selector(projectWizard), discoverabilityTitle: "Create new project"), UIKeyCommand(input: "t", modifierFlags: .command, action: #selector(toolsAction), discoverabilityTitle: "Open Tools"), UIKeyCommand(input: ",", modifierFlags: .command, action: #selector(settingsAction), discoverabilityTitle: "Open Settings"), UIKeyCommand(input: "i", modifierFlags: .command, action: #selector(aboutAction), discoverabilityTitle: "About")
    ]
  }
  else
  {
    return nil
  }
}

ViewController我还有另一个:

override var keyCommands: [UIKeyCommand]?
{
  if #available(iOS 9.0, *)
  {
    return [
      UIKeyCommand(input: "n", modifierFlags: .command, action: #selector(addFileAction), discoverabilityTitle: "New file"), UIKeyCommand(input: "r", modifierFlags: .command, action: #selector(runProject), discoverabilityTitle: "Build and run"), UIKeyCommand(input: "w", modifierFlags: .command, action: #selector(closeProject), discoverabilityTitle: "Close window")
    ]
  }
  else
  {
    return nil
  }
}

当我的应用程序出现ProjectsViewController时,我在 iPad 上按下了 cmd 以显示 Discoverability,它显示了 的组合ProjectsViewController,但是在我打开ViewController并按下 cmd 后,Discoverability 显示了ProjectsViewController和的组合ViewController。如何为每个班级分开键盘快捷键?感谢您的关注。

4

1 回答 1

1

好的,我找到了一个解决方案,也许它不是最好的,但我可以确定它可以正常工作。

在第一个和第二个视图上,定义一个工厂函数来创建你需要的所有命令

viewController1 {

func shortCutKeys() -> [UIKeyCommand] {
        return [
            UIKeyCommand(input: "1", modifierFlags: [], action: #selector(keyInput)),
           ...
            UIKeyCommand(input: "\u{8}", modifierFlags: [], action: #selector(deleteNumber(_:))),
        ]
    }

}

视图控制器2 {

func shortCutKeys() -> [UIKeyCommand] {
        return [
            UIKeyCommand(input: "1", modifierFlags: [], action: #selector(keyInput)),
           ...
            UIKeyCommand(input: "\u{8}", modifierFlags: [], action: #selector(deleteNumber(_:))),
        ]
    }

}

在 viewDidAppear 做类似的事情

 self.shortCutKeys().forEach({
            self.addKeyCommand($0)
        })

在 viewDidDisappear

self.shortCutKeys().forEach({
            self.removeKeyCommand($0)
        })
于 2019-10-09T13:49:17.353 回答