[swift] Swift presentViewController

I programatically have multiple View Controllers in an iOS Swift Project. I do not have the storyboards and would like to avoid them if possible. Is there a way to switch to another viewcontroller.swift file (We will call it view2.swift) and have it be part of a function that a button calls?
I have tried the following:

let storyboard: UIStoryboard = UIStoryboard(name: "myTabBarName", bundle: nil)
let vc: UIViewController = storyboard.instantiateViewControllerWithIdentifier("myVCID") as UIViewController
self.presentViewController(vc, animated: true, completion: nil)

The above works with storyboards, but I want another view2.swift to be called. Can this be done?

This question is related to swift ios8 viewcontroller presentviewcontroller

The answer is


You don't need to instantiate the ViewController in Storyboard just to get present() ViewController to work. That's a hackish solution.

If you see a black/blank screen when presenting a VC, it might be because you're calling present() from viewDidLoad() in the First/RootViewController, but the first View isn't ready yet.

Call present() from viewDidAppear to fix this, i.e.:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let yourVC = YourViewController()
    self.present(yourVC, animated: true, completion: nil)
}

Once any "View" has appeared in your App, you can start calling present() from viewDidLoad().


Using UINavigationController (as suggested in an answer) is another option, but it might be an overkill to solve this issue. You might end up complicating the user flow. Use the UINavigationController based solution only if you want to have a NavigatonBar or want to return to the previous view controller.


For reference, because this question is one of the first Google result.

Breaking change in Swift 3:

The method presentViewController is replaced by the method present.

You can use it like the old one:

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

Example to open the camera:

let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)

Another possibility is that you do not have the XIB included in your Build target (which is what happened to me).

This could happen if you have a different target for Dev, Test & Release Builds (which you should have anyway).


You can use below code :

var vc = self.storyboard?.instantiateViewControllerWithIdentifier("YourViewController") as! YourViewController;
            vc.mode_Player = 1
            self.presentViewController(vc, animated: true, completion: nil)

I had a similar issue but in my case, the solution was to dispatch the action as an async task in the main queue

DispatchQueue.main.async {
    let vc = self.storyboard?.instantiateViewController(withIdentifier: myVCID) as! myVCName
    self.present(vc, animated: true, completion: nil)
}

You can use code:

if let vc = self.storyboard?.instantiateViewController(withIdentifier: "secondViewController") as? secondViewController {
   let appDelegate = UIApplication.shared.delegate as! AppDelegate
   appDelegate.window?.rootViewController = vc
}

Just use this : Make sure using nibName otherwise preloaded views of xib will not show :

var vc : ViewController = ViewController(nibName: "ViewController", bundle: nil) //change this to your class name

 self.presentViewController(vc, animated: true, completion: nil)

For me, I had two views in two separate nav controllers. I had to use a combination of the above.

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

Swift 3.x

        let secondVC = self.storyboard?.instantiateViewController(withIdentifier: "VC-ID" as! yourViewController
        let navigationVC = UINavigationController(rootViewController: secondVC)
        self.present(navigationVC, animated: true, completion: nil)

Solved the black screen by adding a navigation controller and setting the second view controller as rootVC.

let vc = ViewController()       
var navigationController = UINavigationController(rootViewController: vc)
self.presentViewController(navigationController, animated: true, completion: nil

For those getting blank/black screens this code worked for me.

    let vc = self.storyboard?.instantiateViewController(withIdentifier: myVCID) as! myVCName
    self.present(vc, animated: true, completion: nil)

To set the "Identifier" to your VC just go to identity inspector for the VC in the storyboard. Set the 'Storyboard ID' to what ever you want to identifier to be. Look at the image below for reference.


Swift 3 and Swift 4

let vc = self.storyboard?.instantiateViewController(withIdentifier: "idMyViewControllerName") as! MyViewControllerName
self.present(vc, animated: true, completion: nil)

Using Swift 2.1+

 let vc = self.storyboard?.instantiateViewControllerWithIdentifier("settingsVC") as! SettingsViewController
 self.presentViewController(vc, animated: true, completion: nil)

enter image description here


Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to ios8

Is there any way to show a countdown on the lockscreen of iphone? How to display an activity indicator with text on iOS 8 with Swift? How to call gesture tap on UIView programmatically in swift Changing the Status Bar Color for specific ViewControllers using Swift in iOS8 Can I set the cookies to be used by a WKWebView? UIAlertController custom font, size, color How to force view controller orientation in iOS 8? How to get textLabel of selected row in swift? Launch Image does not show up in my iOS App NavigationBar bar, tint, and title text color in iOS 8

Examples related to viewcontroller

Presenting modal in iOS 13 fullscreen Swift programmatically navigate to another view controller/scene Swift: Reload a View Controller How do I create a view controller file after creating a new view controller? presenting ViewController with NavigationViewController swift Programmatically switching between tabs within Swift How to dismiss ViewController in Swift? Swift presentViewController How to Navigate from one View Controller to another using Swift

Examples related to presentviewcontroller

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift Swift presentViewController iOS: present view controller programmatically How to call a View Controller programmatically? modal View controllers - how to display and dismiss