Swift ios set a new root view controller

前端 未结 20 815
醉话见心
醉话见心 2020-12-13 04:46

I wonder if its possible to set a new root VC?

My app gets init with a uinavigation controller that has a table view to be the root VC.

Then from the table v

相关标签:
20条回答
  • 2020-12-13 04:59

    Swift 4

     let storyBoard = UIStoryboard(name: "Your_Storyboard_Name", bundle:Bundle.main)
     self.window = UIWindow(frame: UIScreen.main.bounds)
     let yourVc = storyBoard.instantiateViewController(withIdentifier: "YourIdentifier") as? YourViewController
     if let window = window {
      window.rootViewController = yourVc
       }
     self.window?.makeKeyAndVisible()
    
    0 讨论(0)
  • 2020-12-13 05:02

    Just write this and you are good to go.

    let sb = UIStoryboard(name: "Main", bundle: nil)
    let VC = sb.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
    let navRootView = UINavigationController(rootViewController: VC)
    self.present(navRootView, animated: true, completion: nil)
    
    0 讨论(0)
  • 2020-12-13 05:03

    You can use this code when you click the login button :-

    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    var vc = mainStoryboard.instantiateViewControllerWithIdentifier("respectiveIdentifier") as ViewController  
    UIApplication.sharedApplication().keyWindow.rootViewController = vc
    
    0 讨论(0)
  • 2020-12-13 05:05

    You can use this bit of code:

    let newViewController = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
    
    let customViewControllersArray : NSArray = [newViewController]
    self.navigationController?.viewControllers = customViewControllersArray as! [UIViewController]
    self.navigationController?.pushViewController(newViewController, animated: true)
    
    0 讨论(0)
  • 2020-12-13 05:07

    Swift 3 Update:-

    let testController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "testController") as! TestController
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.window?.rootViewController = testController
    
    0 讨论(0)
  • 2020-12-13 05:07

    UINavigationController has a viewControllers property, which is a NSArray, And you can replaced it with your own NSArray of view controllrs.

    This can be done as show in below sample code.

    let newViewController = self.storyboard?.instantiateViewControllerWithIdentifier("YourViewControllerollerID") as! YourViewController
    
        let customViewControllersArray : NSArray = [newViewController]
        self.navigationController?.viewControllers = customViewControllersArray as! [UIViewController]
    

    And if you want to show this new root view controller you can just call UINavigationController's popToRootViewController() method.

    self.navigationController?.popToRootViewControllerAnimated(true)
    
    0 讨论(0)
提交回复
热议问题