sathish
sathish

Reputation: 1190

How to Navigate from one View Controller to another using Swift

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];

Upvotes: 94

Views: 316628

Answers (16)

Rashid Latif
Rashid Latif

Reputation: 2901

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
    }
}
// Make a ViewController extension to use on all of your ViewControllers
extension UIViewController: Storyboarded {}

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

Upvotes: 2

Navdeep Paliwal
Navdeep Paliwal

Reputation: 379

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)

Upvotes: 3

David K
David K

Reputation: 103

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!

Upvotes: -1

Shanu Singh
Shanu Singh

Reputation: 395

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

Upvotes: 6

KPK
KPK

Reputation: 160

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)
}

Upvotes: 1

Jerry Chong
Jerry Chong

Reputation: 9240

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.

Upvotes: 2

Naresh
Naresh

Reputation: 17932

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) 
} 

Upvotes: 6

Azharhussain Shaikh
Azharhussain Shaikh

Reputation: 1664

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)

Upvotes: 1

Audrey Sobgou Zebaze
Audrey Sobgou Zebaze

Reputation: 2870

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)

Upvotes: 233

Protocol
Protocol

Reputation: 1792

In swift 4.0

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

Upvotes: 8

Davender Verma
Davender Verma

Reputation: 21

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

Upvotes: 2

Zeeshan
Zeeshan

Reputation: 51

In swift 3

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

Upvotes: 3

Saurav Kumar
Saurav Kumar

Reputation: 256

Swift 3

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

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

Upvotes: 3

Yaroslav Dukal
Yaroslav Dukal

Reputation: 3942

SWIFT 3.01

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

Upvotes: 17

Mojtaba Yeganeh
Mojtaba Yeganeh

Reputation: 2922

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

Upvotes: 37

Keith Holliday
Keith Holliday

Reputation: 1732

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)

Upvotes: 19

Related Questions