代码之家  ›  专栏  ›  技术社区  ›  user4992124

向所有uiviewcontroller添加变量

  •  0
  • user4992124  · 技术社区  · 6 年前

    我对斯威夫特不熟悉,我正在努力实现一个习惯 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 ui视图控制器 have that variable? Just like all controllers can override keycommands`默认情况下?

    2 回复  |  直到 6 年前
        1
  •  1
  •   LOKESH KUMAR PEDDA    6 年前

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

    确保变量是唯一的,这样就不会意外地重写它。

    谢谢您。

        2
  •  0
  •   Md. Sulayman    6 年前

    可以创建扩展名 UIViewController 并将该属性添加到 ui视图控制器 . 然后你会在子视图控制器上得到它,比如 UISplitViewController 或者其他习俗 视图控制器 . 要了解更多关于扩展的信息, Which can be added on extension or what can be done by extension??