How to Navigate from one View Controller to another using Swift

IosSwiftUinavigationcontrollerUikitViewcontroller

Ios Problem Overview


I'd like to navigate from one view controller to another. How can I convert the following Objective-C code into Swift?

UIViewController *viewController = [[self storyboard] instantiateViewControllerWithIdentifier:@"Identifier"];
UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:viewController];
[self.navigationController pushViewController:navi animated:YES];

Ios Solutions


Solution 1 - Ios

Create a swift file (SecondViewController.swift) for the second view controller and in the appropriate function type this:

let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as SecondViewController
self.navigationController.pushViewController(secondViewController, animated: true)


Swift 2+
let mapViewControllerObj = self.storyboard?.instantiateViewControllerWithIdentifier("MapViewControllerIdentifier") as? MapViewController
self.navigationController?.pushViewController(mapViewControllerObj!, animated: true)

Swift 4
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "IKDetailVC") as? IKDetailVC
self.navigationController?.pushViewController(vc!, animated: true)

Solution 2 - Ios

In my experience navigationController was nil so I changed my code to this:

let next = self.storyboard?.instantiateViewControllerWithIdentifier("DashboardController") as! DashboardController
self.presentViewController(next, animated: true, completion: nil)

Don't forget to set ViewController StoryBoard Id in StoryBoard -> identity inspector

Solution 3 - Ios

If you don't want the back button to appear (which was my case, because I wanted to present after a user logged in) here is how to set the root of the nav controller:

let vc = self.storyboard?.instantiateViewControllerWithIdentifier("YourViewController") as! YourViewController
        let navigationController = UINavigationController(rootViewController: vc)
        self.presentViewController(navigationController, animated: true, completion: nil)

Solution 4 - Ios

SWIFT 3.01

let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "Conversation_VC") as! Conversation_VC
self.navigationController?.pushViewController(secondViewController, animated: true)

Solution 5 - Ios

In swift 4.0

var viewController: UIViewController? = storyboard().instantiateViewController(withIdentifier: "Identifier")
var navi = UINavigationController(rootViewController: viewController!)
navigationController?.pushViewController(navi, animated: true)

Solution 6 - Ios

In Swift 4.1 and Xcode 10

Here AddFileViewController is second view controller.

Storyboard id is AFVC

let next = self.storyboard?.instantiateViewController(withIdentifier: "AFVC") as! AddFileViewController
self.present(next, animated: true, completion: nil)

//OR

//If your VC is DashboardViewController
let dashboard = self.storyboard?.instantiateViewController(withIdentifier: "DBVC") as! DashboardViewController
self.navigationController?.pushViewController(dashboard, animated: true)

If required use thread.

Ex:

DispatchQueue.main.async { 
    let next = self.storyboard?.instantiateViewController(withIdentifier: "AFVC") as! AddFileViewController
    self.present(next, animated: true, completion: nil) 
}

If you want move after some time.

EX:

//To call or execute function after some time(After 5 sec)
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
    let next = self.storyboard?.instantiateViewController(withIdentifier: "AFVC") as! AddFileViewController
    self.present(next, animated: true, completion: nil) 
} 

Solution 7 - Ios

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let home = storyBoard.instantiateViewController(withIdentifier: "HOMEVC") as! HOMEVC
navigationController?.pushViewController(home, animated: true);

Solution 8 - Ios

Swift 3

let secondviewController:UIViewController =  self.storyboard?.instantiateViewController(withIdentifier: "StoryboardIdOfsecondviewController") as? SecondViewController

self.navigationController?.pushViewController(secondviewController, animated: true)

Solution 9 - Ios

In swift 3

let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "NextViewController") as! NextViewController        
self.navigationController?.pushViewController(nextVC, animated: true)

Solution 10 - Ios

let objViewController = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
self.navigationController?.pushViewController(objViewController, animated: true)

Solution 11 - Ios

Swift 5

Use Segue to perform navigation from one View Controller to another View Controller:

performSegue(withIdentifier: "idView", sender: self)

This works on Xcode 10.2.

Solution 12 - Ios

Swift 4

You can switch the screen by pushing navigation controller first of all you have to set the navigation controller with UIViewController

let vc = self.storyboard?.instantiateViewController(withIdentifier: "YourStoryboardID") as! swiftClassName
     
self.navigationController?.pushViewController(vc, animated: true)

Solution 13 - Ios

In AppDelegate you can write like this...

var window: UIWindow?

fileprivate let navigationCtrl = UINavigationController()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    self.createWindow()
    
    self.showLoginVC()
    
    return true
}

func createWindow() {
    let screenSize = UIScreen.main.bounds
    self.window = UIWindow(frame: screenSize)
    self.window?.backgroundColor = UIColor.white
    self.window?.makeKeyAndVisible()
    self.window?.rootViewController = navigationCtrl
}

func showLoginVC() {
    let storyboardBundle = Bundle.main
    // let storyboardBundle = Bundle(for: ClassName.self) // if you are not using main application, means may be you are crating a framework or library you can use this statement instead
    let storyboard = UIStoryboard(name: "LoginVC", bundle: storyboardBundle)
    let loginVC = storyboard.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC
    navigationCtrl.pushViewController(loginVC, animated: false)
}

Solution 14 - Ios

Better practices Swift 5.0

More reusable and readable

Create a protocol

protocol Storyboarded { }

Now create an extension of the protocol

extension Storyboarded where Self: UIViewController {
    
    static func instantiateFromMain() -> Self {
        let storyboardIdentifier = String(describing: self)
        // `Main` can be your stroyboard name.
        let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        
        guard let vc = storyboard.instantiateViewController(withIdentifier: storyboardIdentifier) as? Self else {
            fatalError("No storyboard with this identifier ")
        }
        return vc
    }
}

How to use

  let vc = MyViewController.instantiateFromMain()
  //here you can pass any data to the next view controller. for example we have a variable with name `myString` in our next view contoller and we want to pass the data my `self viewController`
  vc.myString = "This string passed by MyViewController"
  self.navigationController?.pushViewController(vc, animated: true)

Note:- You need to give the same identifier on the storyboard as your UIViewController class has. Check the example below

enter image description here

Solution 15 - Ios

For Swift 4 & 5 Users can use this way

> Swift 5

 let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
 let vc = storyBoard.instantiateViewController(withIdentifier: "YourViewController") as! YourViewController
 self.navigationController?.pushViewController(vc, animated: true)

> Swift 4

let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "YourViewController") as? YourViewController 
self.navigationController?.pushViewController(vc!, animated: true)

Solution 16 - Ios

Update for Swift 5:

    let next = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController

    self.present(next, animated: true, completion: nil)

Don't forget to update the Storyboard ID for both View Controllers!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsathishView Question on Stackoverflow
Solution 1 - IosAudrey Sobgou ZebazeView Answer on Stackoverflow
Solution 2 - IosMojtaba YeganehView Answer on Stackoverflow
Solution 3 - IosKeith HollidayView Answer on Stackoverflow
Solution 4 - IosYaroslav DukalView Answer on Stackoverflow
Solution 5 - IosProtocolView Answer on Stackoverflow
Solution 6 - IosNareshView Answer on Stackoverflow
Solution 7 - IosShanu SinghView Answer on Stackoverflow
Solution 8 - IosSAURAVView Answer on Stackoverflow
Solution 9 - IosZeeshanView Answer on Stackoverflow
Solution 10 - IosDavender VermaView Answer on Stackoverflow
Solution 11 - IosJerry ChongView Answer on Stackoverflow
Solution 12 - IosAzharhussain ShaikhView Answer on Stackoverflow
Solution 13 - IosKPKView Answer on Stackoverflow
Solution 14 - IosRashid LatifView Answer on Stackoverflow
Solution 15 - IosNavdeep PaliwalView Answer on Stackoverflow
Solution 16 - IosDavid KView Answer on Stackoverflow