您可以将数据从您的第一个视图控制器传递到嵌入的视图控制器,如下所示 UITabbarController。
UITabBarController -> UINavigationController -> UIViewController
需要遍历UITabBarController和UINavigationController的viewControllers实例,才能得到UIViewController的实例。一旦您获得嵌入到UITabbarController 中的“UIViewController”实例,您就可以根据需要分配数据。
举例
if let tabBarController = self.storyboard?.instantiateViewControllerWithIdentifier("mainNavID") as? UITabBarController {
// Now you need to get View Controllers array from tabBarControllers which is UINavigationControllers
if let navigationControllers = tabBarController.viewControllers as? [UINavigationController] {
for navigationController in navigationControllers {
//Now you need to get the viewControllers from navigationController stack,
let viewControllers = navigationController.viewControllers
//Now you can assing desired value in viewControllers, I am assuming you need to assign the same value in all viewControler
for viewController in viewControllers {
}
}
}
}
在这种架构中使用 Singleton 传递数据的最佳方式,假设您创建了一个类Session,其中成员变量token。
class Session {
//Singleton
static let sharedInstance = Session()
//Token which you assign and you can use through out application
var token : String? = nil
}
现在,您可以在推送UITabbarController 时分配令牌。
let openNewVC = self.storyboard?.instantiateViewControllerWithIdentifier("mainNavID") as! UITabBarController
Session.sharedInstance.token = token
//openNewVC.token = token!
self.navigationController?.pushViewController(openNewVC, animated: true)
您可以在 UIViewController 中使用相同的令牌
override func viewDidLoad() {
super.viewDidLoad()
if let token = Session.sharedInstance.token {
//Now you have assigned token
}
}