简体   繁体   中英

Pass data from tableview to tab bar view controller in Swift.

At my storyboard I have a part where a view controller with a table view is placed before a tab bar controller. This tab bar has two view controllers. Earlier I used the table view already, and when I clicked on one cell I passed to another Viewcontroller which loaded another view controller with table and cells with the id from the pushed cell from the first table. Like this:

The tableview controller, prepare for segue:

        if segue.identifier == "overviewSegue" {
          var caseViewController: CaseViewController = segue.destinationViewController as CaseViewController
          var caseIndex = overviewTableView!.indexPathForSelectedRow()!.row
          var selectedCase = self.cases[caseIndex]
        caseViewController.caseitem = selectedCase
    }

This works well. Now I want to do the same, but the only difference is that the last view controller is part of a tabbar controller. The problem is I can't get it working to pass the data to this last table view controller.

I tried several things, but I can't point the data to the tabbar table view. Segue's are not approachable, and the destination isn't the table view controller, but the tabbar controller, etc. The question, how to pass data from a tableview through the tabbar controller to another view controller.

I have found a solution:

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
      if segue.identifier == "toTabController" {
        var tabBarC : UITabBarController = segue.destinationViewController as UITabBarController
        var desView: CaseViewController = tabBarC.viewControllers?.first as CaseViewController

        var caseIndex = overviewTableView!.indexPathForSelectedRow()!.row
        var selectedCase = self.cases[caseIndex]

        desView.caseitem = selectedCase
      }
    }

Easy explanation: You need to get to your Tab bar controller and pick his view controllers. It normally has two, so you can pick the first. After that, define which class it belongs to, and you can pass your data just as you did before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM