在ViewController和TabBarController之间传递数据

时间:2016-09-14 15:34:18

标签: ios swift uiviewcontroller uitabbarcontroller

我有几个问题。 如何将数据(我在Alamofire请求完成后得到的数据)传递给TabBarController的子节点之一?

我遇到的第一个问题是我无法覆盖登录操作中的func prepareForSegue(当点击按钮时),它表示我只能覆盖类成员。但如果我把功能放在IBAction之外,那么我就不会发送我需要的数据。

第二个问题是,当我将覆盖的函数放在IBAction之外时,代码看起来像这样:

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

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

当我运行它时,我收到错误:

  

无法转换类型' UITabBarController'至   HomeViewController'

(HomeViewController是我的目标视图,我应该从Alamofire传递数据)。

4 个答案:

答案 0 :(得分:12)

您不一定需要使用prepareForSegue。只需在TabBarController viewControllers数组中引用所需的ViewController并将其强制转换。

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

如果TabBar中的ViewControllers嵌入在导航控制器中,您可以这样做:

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

答案 1 :(得分:2)

对于Xcode 8,Swift 3.x,您可以使用以下内容。这假设您将视图控制器嵌入在导航控制器中。在我的情况下,我试图在从新用户设置视图导航时将名为startWizard的变量设置为true。

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
            }
        }
    }
}

答案 2 :(得分:0)

您可以从TabController类(父级)中执行以下操作:

var maleVC: MaleOptionsViewController! //First child 
var femaleVC: FemaleOptionsViewController! //Second child

override func viewDidLoad() {
    super.viewDidLoad()
    maleVC = self.viewControllers![0] as? MaleOptionsViewController //Reference to first child
    femaleVC = self.viewControllers![1] as? FemaleOptionsViewController //Reference to second child
}

并像这样传递数据:

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        maleVC.cartTableView?.reloadData() //Where cartTableView is an IBOutlet or even a variable for that matter
        femaleVC.cartTableView?.reloadData() //Same thing as the comment ^
}

答案 3 :(得分:-1)

更改标签栏选择索引并将数据发送到该ViewController

tabBarController!.selectedIndex = 2
let navVC = tabBarController!.viewControllers![2] as! UINavigationController

let SV = navVC.topViewController as! SearchViewController
SV.selectedIndex = indexPath.row