1

I have a button with the following code:

@IBAction func buttonPress(sender: AnyObject) {
    performSegueWithIdentifier("newAccount", sender: sender)
}

When the button is pressed it performs a segue. I want to pass a value to the new view controller so I added the following code:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "newAccount" {
        if let dvc = segue.destinationViewController as? NewAccountViewController {
            dvc.testValue = "This is my test value I want to pass"
        }
    }
}

The NewAccountViewController doesn't receive the value (I don't get any error).

The code I have in my NewAccountViewController is:

var testValue:String?

When I print(testValue) I don't get anything.

Why isn't this working as expected?

user1822824
  • 2,478
  • 6
  • 41
  • 65
  • Have you checked that you set the class of destinationViewController to `NewAccountViewController` in storyboard ? – Leo Mar 02 '16 at 05:32
  • 1
    Have you put a breakpoint on `dvc.testValue` to see if it's being executed? Maybe the `if let` fails, or the case of `segue.identifier` is different. You shouldn't need to test the identifier on the assumption the `if let` will only work for the right VC. – Michael Mar 02 '16 at 05:39
  • @Michael It looks like the if let part fails. I added print("test if let") to the if let statement and it does not print. – user1822824 Mar 02 '16 at 05:41
  • @Leo I am not sure I follow. How can I confirm that? – user1822824 Mar 02 '16 at 05:42
  • So as @Leo points out, you probably haven't set the class of the VC. – Michael Mar 02 '16 at 05:42
  • @user1822824 See the image I post below. – Leo Mar 02 '16 at 05:45
  • your `if segue.identifier == "newAccount"` is satisfied , if yes `if let dvc = segue.destinationViewController as? NewAccountViewController` condition is statisfied or not – Anbu.Karthik Mar 02 '16 at 05:46
  • @Leo Thanks. That fixed it. – user1822824 Mar 02 '16 at 05:48

2 Answers2

3

You need to check if the class is set correctly

Like the ViewController in below image

enter image description here

Leo
  • 24,596
  • 11
  • 71
  • 92
0

There are maybe two reasons: 1. identifier is not set as "newAccount" in the storyboard; 2. you have put a navigator view controller into the NewAccountViewController, which would ask you to transfer the destination as UINavigationController instead of NewAccountViewController. Hope this helps.

James Rao
  • 168
  • 2
  • 13