将变量添加到所有 UIViewControllers
Posted
技术标签:
【中文标题】将变量添加到所有 UIViewControllers【英文标题】:add variable to all UIViewControllers 【发布时间】:2018-07-12 09:26:42 【问题描述】:我是 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
UIViewControllerhave that variable? Just like all controllers can override
keyCommands`?
【问题讨论】:
【参考方案1】:您必须创建一个带有命令变量的协议,并使您的视图控制器符合它(第 1 步)。您可以为特定视图控制器提供值,也可以提供默认实现。
第 1 步:- 使用您需要的变量创建协议。
protocol Commandable
var commands: [String]set get
extension Commandable
var commands: [String]
getreturn ["hello","world"]
set
第 2 步:- 然后使您使用的控制器符合它
第 3 步:- 更改上述代码以获取命令
if let commandProtocol = masterVC as? Commandable
let commands = commandProtocol.commands
else
// handle it
确保变量是唯一的,以免意外覆盖它。
谢谢。
【讨论】:
【参考方案2】:您可以创建UIViewController
的扩展名并将该属性添加到UIViewController
的扩展名上。然后,您将在 UISplitViewController
或任何其他自定义 ViewControllers 等子视图控制器上获得它。想了解更多关于扩展的信息,Which can be added on extension or what can be done by extension??
【讨论】:
以上是关于将变量添加到所有 UIViewControllers的主要内容,如果未能解决你的问题,请参考以下文章
如何将 UIViewController 作为子视图添加到 UIViewController(RootViewController)?
将带有 ScrollView 和 AutoLayout 的 UIViewController 添加到另一个 UIViewController
在 `UIViewController` 上方添加 `UIView`
将 UIViewController 添加到 UIScrollView