Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Segue programmatically in Swift

Tags:

ios

swift

segue

I have two VCs: VC1 and VC2. In VC1, I have a finish button which I programmatically made and a result array I want to pass to VC2.

I know how to make Segue in Storyboard, but I cannot do that at this moment since the finish button is programmatically made.

If I want to pass result array using segue, is there a way to make the segue programmatically? If this is not possible, should I just present VC2 using presentViewController and set a delegate to pass the result array?

like image 567
Kahsn Avatar asked Feb 11 '16 20:02

Kahsn


People also ask

What is perform segue in Swift?

Swift version: 5.6. Segues are a visual way to connect various components on your storyboard, but sometimes it's important to be able to trigger them programmatically as well as after a user interaction.

How can segue be executed in IOS application?

To create a segue between view controllers in the same storyboard file, Control-click an appropriate element in the first view controller and drag to the target view controller. The starting point of a segue must be a view or object with a defined action, such as a control, bar button item, or gesture recognizer.

How do I segue to another view controller?

Well, in addition to that, Ctrl+dragging also helps set up segues. So, Ctrl+Drag from the “Go to Other View Controller” button, to somewhere in the second View Controller. It can be anywhere in the main box of the second view controller. When you release, it will show you a box like the one below.


1 Answers

You can do it like proposed in this answer: InstantiateViewControllerWithIdentifier.

Furthermore I am providing you the code from the linked answer rewritten in Swift because the answer in the link was originally written in Objective-C.

let vc = UIStoryboard(name:"Main", bundle:nil).instantiateViewController(withIdentifier: "identifier") as! SecondViewController

vc.resultsArray = self.resultsArray

EDIT:

Since this answer draws some attention I thought I provide you with another more failsafe way. In the above answer the application will crash if the ViewController with "identifier" is not of type SecondViewController. In Swift you can prevent this crash by using optional binding:

guard let vc = UIStoryboard(name:"Main", bundle:nil).instantiateViewControllerWithIdentifier("identifier") as? SecondViewController else {
    print("Could not instantiate view controller with identifier of type SecondViewController")
    return
}

vc.resultsArray = self.resultsArray
self.navigationController?.pushViewController(vc, animated:true)

This way the ViewController is pushed if it is of type SecondViewController. If can not be casted to SecondViewController a message is printed and the application remains on the current ViewController.

like image 89
dehlen Avatar answered Sep 26 '22 06:09

dehlen