我是 Swift 新手,我正在尝试UIKeyCommand
在练习应用程序中实现自定义架构。我为基础编写了下面的扩展,以在屏幕上的当前视图中UISplitViewController
显示所有内容。UIKeyCommands
extension UISplitViewController {
open override var canBecomeFirstResponder: Bool {
return true
}
var BPKeyCommands: [BPKeyCommand]? {
var commands: [BPKeyCommand] = []
var mastervc = self.viewControllers.first
if (mastervc is UINavigationController) {
mastervc = (mastervc as! UINavigationController).viewControllers.last
}
if let masterCommands = mastervc.commands {
for command in masterCommands {
commands.append(command)
}
}
return commands
}
open override var keyCommands: [UIKeyCommand]? {
var commands: [UIKeyCommand] = []
if let bpkeycommands = BPKeyCommands {
for command in bpkeycommands {
let new = UIKeyCommand(input: command.input,
modifierFlags: command.modifierFlags,
action: #selector(executeKeyCommand(sender:)),
discoverabilityTitle: command.title)
commands.append(new)
}
}
return commands
}
@objc private func executeKeyCommand(sender: UIKeyCommand) {
if let index = keyCommands?.firstIndex(of: sender) {
if let command = BPKeyCommands?[index] {
command.action(command)
}
}
}
}
现在,正如您所料,这会引发错误if let masterCommands = mastervc.commands {
,因为UIViewController doesn't contain the commands variable out of the box. My question is: how can I have
UIViewController have that variable? Just like all controllers can override
keyCommands` 默认情况下?