Andy Lebowitz
Andy Lebowitz

Reputation: 1501

Issue: Transferring View Controllers through segue depending on what button is pushed

My issue is that I have two view controllers, and I need to transfer a string from one view controller to the next. I already have that down from a segue. The actual issue is that I need a label to change in the next view controller to make it match the currentTitle of the button in the previous view. And yes, there are multiple buttons.

My code from view 1 is this:

@IBAction func whichButtonWasClicked(sender: AnyObject) {
   clickedButton = sender.currentTitle!!
}

// Segue - Pass the Data of which lesson was chosen
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let DestViewController : Lesson = segue.destinationViewController as! Lesson
    DestViewController.lessonPlan = clickedButton
}

I connected all my 7 buttons to that same one action. The problem is that when I transfer view controllers, and do...

print(lessonPlan)

It does not give me the title of the button from the action, because I guess that action is after the segue. And yes I tested it, and it IS after the segue. SO it does work, it's just a bit delayed, and I need it to be a part of the segue.

Upvotes: 0

Views: 28

Answers (1)

Dominic K
Dominic K

Reputation: 7085

Since your IBAction is being called after prepareForSegue, you can use programmatic segues.

Right now, you're probably dragging a segue from your button to the next view controller. Instead, you can drag a segue from the current view controller to the next one (see this answer for a visual guide). This will create a programmatic segue that you can trigger whenever you'd like from code. Remember to give the segue an identifier in Xcode.

Then in whichButtonWasClicked, call self.performSegueWithIdentifier("identifier you setin Xcode", sender: sender) after you set clickedButton in order to trigger the segue. By doing so, you'll ensure that your button action is called before the segue starts.

Upvotes: 3

Related Questions