通过一些额外的研究,我想出了一个答案。感谢Will-m 提供我需要的线索。当前对此答案的警告是 TabBarController 加载的第一个视图不会被注入。
为了从 UITabBarController 向 ViewControllers 注入数据,您需要执行以下操作:
首先,您需要在加载时将 RootViewController 设置为自己的委托。
您不一定需要控制器类作为它自己的委托
除非您需要将所需数据从另一个类直接注入到 UITabBarController。
您还需要将委托类声明为符合UITabBarControllerDelegate 协议。
// Declare UITabBarControllerDelegate protocol
class RootViewController: UITabBarController, UITabBarControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Set class delegate to self
self.delegate = self
}
}
您需要设置 RootViewController 的委托,因为
委托的协议包含一个重要的方法:
tabBarController(_:shouldSelectViewController:)。这种方法是
当 RootViewController 更改其活动选项卡时调用。
tabBarController(_:shouldSelectViewController:) 的“viewController”参数是 TabBarController 切换到的子 ViewController 的实例。如果您已为该 ViewController 分配了协议(以便编译器知道您的变量已在类中声明),您可以将变量注入子级。
所以像这样将函数添加到 RootViewController 类中:
func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) {
// Get your view controller using the correct protocol.
// Use guard to make sure the correct type of viewController has been provided.
guard let vc = viewController as? YourProtocol
else { fatalError("wrong view controller type") }
// Assign the protocol variable to whatever you want injected into the class instance.
vc.VariableInYourProtocol = InjectedVariable
}
就是这样。如果您需要支持不同协议的控制器,我可能会写一些关于使用 switch 语句来做到这一点的东西。那
到目前为止,这还不是我需要使用的东西。
另外,请注意,此方法适用于 CoreData 实践,其中只有一个 managedObjectContext 实例在活动 ViewController 之间传递。使用此方法而不是直接从每个 ViewController 的应用程序委托中检索上下文的不同实例。