如何将值从 navigationController 传递到 TabBarController

How to pass value from navigationController to TabBarController

我有一个登录项目。第一个视图控制器是 NavController,我需要将用户数据传递给 tabBarController,我有 3 个 NavigationController。

我试过了。

let openNewVC = self.storyboard?.instantiateViewControllerWithIdentifier("mainNavID") as! UITabBarController
//openNewVC.token = token!
self.navigationController?.pushViewController(openNewVC, animated: true)

您可以尝试将值设置为 openNewVC,就像设置正常 属性 一样。

示例:

//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)

您可以将数据从您的第一个视图控制器传递到视图控制器,如下所示 UITabbarController

UITabBarController -> UINavigationController -> UIViewController

需要遍历UITabBarControllerUINavigationControllerviewControllers实例,才能得到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传递数据的最佳方式,假设你创建了一个class 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
    }
}