如何从segue中的另一个视图控制器实例化导航和选项卡控制器(显示详细信息)?

时间:2016-06-23 16:53:59

标签: ios swift uiviewcontroller

之前我问过一个问题,并且由于其中一个答案How to instantiate a navigation controller from another view controller?而成功运行,但我遇到了一个新问题,即每当我点击一个显示详细信息的按钮时,它就会出现问题应该导航到带有导航栏的普通标签,但它没有做任何事情。

这是故事板

enter image description here

这是方案

1)用户单击firstViewController上的按钮,它将转到显示详细信息的thirdViewController

2)用户单击另一个按钮,然后该按钮将转到带有以下代码

的secondViewController

这是代码

在ThirdViewController中

@IBAction func buttonTapped(sender: UIButton) {

        guard let tabBarController = tabBarController else { return }
        let navController = tabBarController.viewControllers![1] as! UINavigationController
        let secondViewController = navController.topViewController as! SecondViewController

        secondViewController.name = "My name is TDog"

        tabBarController.selectedIndex = 1


    }

我做错了什么?我还需要实例化吗?

2 个答案:

答案 0 :(得分:1)

你必须忽略实际的ThirdViewController但是,在这个类中,你还不知道UITabViewController所以获得它的方法(不是为了重新实例化而是从内存中调用)就是调用窗口的rootViewController(可以在你的项目中完成):

@IBAction func buttonTapped(sender: AnyObject) {
    self.presentingViewController!.dismissViewControllerAnimated(true, completion: nil)
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let tabBarController = appDelegate.window!.rootViewController
    if tabBarController is UITabBarController {
        let tab = tabBarController as! UITabBarController
        let navController = tab.viewControllers![1] as! UINavigationController
        let secondViewController = navController.topViewController as! SecondViewController
        secondViewController.nameString = "My name is TDog"
        tab.selectedIndex = 1
    }
}

答案 1 :(得分:0)

你必须打电话

self.presentingViewController.dismissViewControllerAnimated(true, completion: nil)

以下一行后

tabBarController.selectedIndex = 1