How to instantiate a navigation and tab controller

2019-07-29 11:45发布

I've asked a question before and it works successfully thanks to the one of the answers How to instantiate a navigation controller from another view controller?, but I have come across a new problem which is , whenever i click a button from a show detail segue, it supposed to navigate to a normal tab with a navigation bar, but it did nothing.

Here's the storyboard

enter image description here

Here's the scenario

1) User click on a button on a firstViewController and it will segue to a thirdViewController which is in show detail

2) User click another button which will then supposed to go to a secondViewController with the codes below

Here's the code

in 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


    }

What did i do wrong? Do i still need to instantiate?

2条回答
欢心
2楼-- · 2019-07-29 12:06

You have to dismiss the actual ThirdViewController but, in this class, you dont know yet UITabViewController so a way to obtain it ( not to re-instantiate but to recall from memory) is to call the rootViewController of your window (it can be done in your project):

@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
    }
}
查看更多
等我变得足够好
3楼-- · 2019-07-29 12:10

You got to call

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

after the following line

tabBarController.selectedIndex = 1
查看更多
登录 后发表回答