向所有UIViewControllers添加变量

时间:2018-07-12 09:26:42

标签: ios swift properties uikit uikeycommand

我是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`?

2 个答案:

答案 0 :(得分:1)

您必须使用命令变量创建一个协议,并使您的视图控制器符合该协议(步骤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
}

确保变量是唯一的,这样您就不会意外覆盖它。

谢谢。

答案 1 :(得分:0)

您可以创建扩展名 /** * Add checkbox field before shipping calculator **/ add_action('woocommerce_before_shipping_calculator', 'my_checkbox'); function my_checkbox ( 'my_checkbox', array( echo ' 'type' => 'checkbox', 'class' => array('input-checkbox'), 'label' => __('Delivery forwarding'), 'required' => false, ), $checkout->get_value( 'my_checkbox' )); } 并将该属性添加到扩展名UIViewController上。然后,您将在UIViewController之类的子视图控制器或任何其他自定义 ViewControllers 上获得它。要了解有关扩展的更多信息,Which can be added on extension or what can be done by extension??