0

我是 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 haveUIViewController have that variable? Just like all controllers can overridekeyCommands` 默认情况下?

4

2 回答 2

2

您必须创建一个带有命令变量的协议并使您的视图控制器符合它(步骤 1)。您可以为特定视图控制器提供值,也可以提供默认实现。

第 1 步:- 使用您需要的变量创建协议。

protocol Commandable{
   var commands: [String]{set get}
}
extension Commandable{
   var commands: [String]{
        get{return ["hello","world"]}
        set{}
    }
}

第 2 步:- 使您正在使用的控制器符合它

第 3 步:- 更改上述代码以获取命令

if let commandProtocol = masterVC as? Commandable
{
    let commands = commandProtocol.commands
}
else{
    // handle it
}

确保变量是唯一的,以免意外覆盖它。

谢谢你。

于 2018-07-12T13:03:57.283 回答
0

您可以创建 的扩展名UIViewController并将该属性添加到UIViewController. 然后,您将在子视图控制器UISplitViewController或任何其他自定义ViewControllers上获得它。要了解更多关于扩展的信息,哪些可以添加到扩展上,或者可以通过扩展做什么??

于 2018-07-12T10:00:25.017 回答