Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 697
Z-Tech Avatar asked Jun 07 '14 16:06

Z-Tech


People also ask

How do I present a two view controller in Swift?

For solving this, you will need to do a pretty simple trick which is to take a screenshot from the first view controller and passing it to the second view controller to display it while presenting the third view controller. You can check this repository to see how it is exactly could be done (Swift 3).


3 Answers

Try this:

let vc = ViewController() //change this to your class name
self.presentViewController(vc, animated: true, completion: nil)

With Swift3:

self.present(vc, animated: true, completion: nil)
like image 143
Adam Avatar answered Oct 11 '22 09:10

Adam


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.

like image 111
boidkan Avatar answered Oct 11 '22 10:10

boidkan


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)
like image 21
Arnlen Avatar answered Oct 11 '22 09:10

Arnlen