我在Swift中遇到UIKeyCommand
的问题。我有两个UIViewVontroller
,ProjectsViewController
和ViewController
。我正在使用以下代码从ViewController
中打开ProjectsViewController
:
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的“可发现性”,并显示了ProjectsViewController
的组合,但是在打开ViewController
并按cmd后,可发现性显示了ProjectsViewController
和ViewController
的两种组合。如何为每个班级分开键盘快捷键?感谢您的关注。
答案 0 :(得分:0)
好吧,我找到了一个解决方案,也许它不是最好的,但是我可以确定它能正常工作。
在第一个视图和第二个视图上,定义一个工厂函数,该函数可以创建所需的所有命令
viewController1 {
func shortCutKeys() -> [UIKeyCommand] {
return [
UIKeyCommand(input: "1", modifierFlags: [], action: #selector(keyInput)),
...
UIKeyCommand(input: "\u{8}", modifierFlags: [], action: #selector(deleteNumber(_:))),
]
}
}
viewController2 {
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)
})