Search code examples
iosswiftuinavigationbarviewcontroller

Swift programmatically navigate to another view controller/scene


I'm using following code to programmatically navigate to another ViewController. It works fine, but it some how hides the navigation bar. How do I fix this? (the navigation bar is created by embeding the ViewController in the navigation controller if that matters.)

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("nextView") as NextViewController
self.presentViewController(nextViewController, animated:true, completion:nil)

Solution

  • Swift 5

    The default modal presentation style is a card. This shows the previous view controller at the top and allows the user to swipe away the presented view controller.

    To retain the old style you need to modify the view controller you will be presenting like this:

    newViewController.modalPresentationStyle = .fullScreen
    

    This is the same for both programmatically created and storyboard created controllers.

    Swift 3

    With a programmatically created Controller

    If you want to navigate to Controller created Programmatically, then do this:

    let newViewController = NewViewController()
    self.navigationController?.pushViewController(newViewController, animated: true)
    

    With a StoryBoard created Controller

    If you want to navigate to Controller on StoryBoard with Identifier "newViewController", then do this:

    let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let newViewController = storyBoard.instantiateViewController(withIdentifier: "newViewController") as! NewViewController
            self.present(newViewController, animated: true, completion: nil)