Search code examples
iosswiftuistoryboardsegue

How to pass variable that has been altered with prepareForSegue



How can one pass a variable with prepareForSegue that has been altered since it's instantiation? When I attempt to pass a variable with prepareForSegue it sends the value it is instantiated with, not the value I have altered it to.
Code:

var friendChosen:String!

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if(segue.identifier == "toChat") {
        let theVC: chatViewController = segue.destinationViewController as! chatViewController
        theVC.friendChosen = friendChosen
    }
}

When the user clicks on a button, the friendChosen variable should take the value of a name. It does, and successfully prints it's value to the terminal, however it does not seem to register when the segue is called (after it has been changed).

func chooseFriend(sender: UIButton) {
    let requestIndex = sender.tag
    self.friendChosen = self.friends.objectAtIndex(requestIndex) as! String
}

Solution

  • the chooseFriend UIButton is a segue to the view controller that I am attempting to pass the variable to.

    Since the segue is triggered by UIButton, the call of prepareForSegue happens before the call of UIButton's action, i.e. chooseFriend. The chooseFriend variable has not been set yet, so prepareForSegue sees an empty value.

    You can fix this by combining the two methods into one: cast the sender to UIButton, take its tag, and set the variable, like this:

    override func prepareForSegue(segue: UIStoryboardSegue, senderObj: AnyObject?) {
        if(segue.identifier == "toChat") {
            let sender = senderObj as! UIButton
            let requestIndex = sender.tag
            let theVC: chatViewController = segue.destinationViewController as! chatViewController
            theVC.friendChosen = self.friends.objectAtIndex(requestIndex) as! String
        }
    }