user1269613
user1269613

Reputation: 1

How to pass data to another storyboard in Xcode?

In an iPhone application, how do I pass data from one view (xib file) to another storyboard?

for example,

I have "welcome.xib" which contains nameTextfield and nextButton ,user will type their name into nameTextfield and click next

the app will navigate to "main.storyboard" and display the text from nameTextfield.text on userNameLabel in "main.storyboard"

what I know so far:

Upvotes: 0

Views: 1136

Answers (2)

Ayush Verma
Ayush Verma

Reputation: 169

Swift 4.2+

Add this to the view controller from wherein you want to send the data -

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard
            let destination = segue.destination as? viewControllerName
            else {
                return
        }
        destination.variable =data
    }

Make sure the name of the variable is the same as the one in where you want to send the data to, also the viewControllerName should be exactly similar.

Then use the following to perform the action either on a button click or inside any completionHandler -

self.performSegue(withIdentifier: "viewControllerIdentifierName", sender: nil)

It is important to also make sure that the storyboard connecting the two should have the same identifier name as what you type inside the withIdentifier or the app will crash.

Upvotes: 0

Sam Baumgarten
Sam Baumgarten

Reputation: 2249

Override the -prepareForSegue:sender: method in your ViewController you want to pass the information from.

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    DetailViewController *sc = [segue destinationViewController];
    // Here you can set variables in detailViewController. For example if you had a NSString called name
    sc.name = @"name_here";
    // Or you could do
    [sc setName:@"name_here"];
}

Upvotes: 2

Related Questions