问题
I have a Login project. The first view controller is NavController and I need to pass user data to tabBarController where I have 3 NavigationControllers.
I tried this.
let openNewVC = self.storyboard?.instantiateViewControllerWithIdentifier("mainNavID") as! UITabBarController
//openNewVC.token = token!
self.navigationController?.pushViewController(openNewVC, animated: true)
回答1:
You can pass the data from your first view Controller to view controllers which are embedded like as below in UITabbarController.
UITabBarController -> UINavigationController -> UIViewController
You need to traverse the viewControllers instance of UITabBarController and UINavigationController in order to get the instance of UIViewController. Once you will get the instance of 'UIViewController' which is embedded into UITabbarController, you can assign the data as required.
For Example
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 {
}
}
}
}
The best way to pass the data in this kind of architecture using Singleton, Assume you created a class Session which member variable token.
class Session {
//Singleton
static let sharedInstance = Session()
//Token which you assign and you can use through out application
var token : String? = nil
}
Now, you can assign the token while pushing the UITabbarController.
let openNewVC = self.storyboard?.instantiateViewControllerWithIdentifier("mainNavID") as! UITabBarController
Session.sharedInstance.token = token
//openNewVC.token = token!
self.navigationController?.pushViewController(openNewVC, animated: true)
Same token you can use within UIViewController
override func viewDidLoad() {
super.viewDidLoad()
if let token = Session.sharedInstance.token {
//Now you have assigned token
}
}
回答2:
You could try to set the values to the openNewVC as you would set a normal property.
Example:
//set instance
var openNewVC = self.storyboard?.instantiateViewControllerWithIdentifier("mainNavID") as! UITabBarController
// set properties
openNewVC.myFancyString = "Hello world!"
// set view controller active
self.navigationController?.pushViewController(openNewVC, animated: true)
来源:https://stackoverflow.com/questions/33373187/how-to-pass-value-from-navigationcontroller-to-tabbarcontroller