Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Values to UIViewController in new Storyboard - Swift

I am trying to pass values to a new view controller - located within a new storyboard file. However when I do so, the result I get from the NewViewController is always nil.

Below is how I show the view controller within the new storyboard:

// Show create account page with custom transition
var storyboard : UIStoryboard = UIStoryboard(name: StoryboardName, bundle: nil)
var vc : UIViewController = storyboard.instantiateViewControllerWithIdentifier(NewViewController) as UIViewController

I try to send the information here:

// Pass the delegate to the first view controller
let newViewController:NewViewController = NewViewController()
newViewController.createAccountDelegate = self
newViewController.teststring = "hello"

And then present the view controller.

vc.transitioningDelegate = self
vc.modalTransitionStyle = UIModalTransitionStyle.CoverVertical
self.presentViewController(vc, animated: true, completion: nil)

Here is my NewViewController, where I try to receive the values. However end up still being nil.

import UIKit

class NewViewController: UIViewController {
    var createAccountDelegate:AccountCreationDelegate!
    var teststring:NSString!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

Am I sending the values incorrectly?

like image 979
Ryan Avatar asked Aug 15 '14 10:08

Ryan


People also ask

How do I pass value from one ViewController to another in swift?

If you have a value in one view controller and want to pass it to another, there are two approaches: for passing data forward you should communicate using properties, and for passing data backwards you can either use a delegate or a block.


1 Answers

You are creating a new instance of NewViewController with this line

let newViewController:NewViewController = NewViewController()

Instead assign variables and delegate to vc which you have instantiated from StoryBoard

var storyboard : UIStoryboard = UIStoryboard(name: StoryboardName, bundle: nil)
// It is instance of  `NewViewController` from storyboard 
var vc : NewViewController = storyboard.instantiateViewControllerWithIdentifier(NewViewController) as NewViewController

// Pass delegate and variable to vc which is NewViewController
vc.createAccountDelegate = self
vc.teststring = "hello"
vc.transitioningDelegate = self
vc.modalTransitionStyle = UIModalTransitionStyle.CoverVertical
self.presentViewController(vc, animated: true, completion: nil)
like image 103
codester Avatar answered Sep 20 '22 23:09

codester