Pass data between ViewController and TabBarController

独自空忆成欢 提交于 2019-12-21 04:51:33

问题


I have couple of questions. How to pass the data (which i got after the Alamofire request is finished), to one of children of TabBarController?

The first problem i have is that i can't override the func prepareForSegue inside login action(when the button is tapped), it says i can override only class members. But if i put the func outside of IBAction then i won't send the data that i need.

And the second problem is, when i put the overrided function outside of IBAction, and the code look like this:

 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {

            let homeVC = segue.destinationViewController as HomeViewController
            homeVC.templateForCell = templates
        }

when i run it, i got the error:

Could not cast value of type 'UITabBarController' to HomeViewController'

(HomeViewController is my destination view, where i should pass the data from Alamofire).


回答1:


You don't necessarily need to use prepareForSegue for this. Just reference which ViewController in the TabBarController viewControllers array that you want and cast it.

let vc = self.tabBarController.viewControllers![1] as! HomeViewController
vc.templateForCell = templates

If the ViewControllers in your TabBar are embedded in Navigation Controllers, you can do this:

let navController = self.tabBarController.viewControllers![1] as! UINavigationController
let vc = navController.topViewController as! HomeViewController
vc.templateForCell = templates



回答2:


For Xcode 8, Swift 3.x you can use something like the following. This assumes you have your view controller embedded in a navigation controller. In my situation, I am trying to set a variable called startWizard to true when navigating from the new user setup view.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "segueFromNewUserToDashboard") {
        let dashboardController = segue.destination as! MyTabBarController
        for viewController in dashboardController.viewControllers! {
            let navViewController = (viewController as! MyNavigationController).topViewController!
            if (navViewController.isKind(of: DashboardViewController.self) == true) {
                (navViewController as! DashboardViewController).startWizard = true
                break
            }
        }
    }
}


来源:https://stackoverflow.com/questions/39494454/pass-data-between-viewcontroller-and-tabbarcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!