Say we have a ViewController (Doctor), and we want to segue to another (Happiness) when the user clicks a Happy or Sad button.

How could we do it?

Add segues.

While holding down the ‘control’ key we can drag from the buttons on the left MVC to the MVC on the right and select the ‘push’ model.

Give segues identifier names.

Assign each segue a name so we can tell one from the other (i.e Happy, Sad).

Add Navigation Controller.

If you ran this now it wouldn’t work. Segues only work when they are within some kind of navigation controller.

Click on the MVC on the left (the one that is going to start the application and go)

Editor -> Embed in -> Navigation Controller

If you run now you should see transitions when you click on Happy/Sad buttons.

Prepare for segue

To pass data to our new MVC we need to set stuff up in our prepareForSeque method.

DoctorViewController.m


#import "DoctorViewController.h"
#import "HappinessViewController.h"

@implementation DoctorViewController

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NSLog(@"prepareForSegue: %@", segue.identifier);

    if ([segue.identifier isEqualToString:@"Happy"]) {
        [segue.destinationViewController setHappiness:100];
    } else if ([segue.identifier isEqualToString:@"Sad"]) {
        [segue.destinationViewController setHappiness:0];
    }
}

@end

In here the segue.destinationViewController points to the ViewController we are going to navigate to and it is of type ‘id’ (a special type in iOS objective C which could be any object).

Because we know where we are navigating to HappinessViewController we can treat segue.destinationViewController as if it were our HappinessViewController and call methods on it like setHappiness.

That’s how we pass data from one MVC to another. Through the segue by calling set property methods directly on our new ViewController.

And we can test that this gets passed by placing a log call in our HappinessViewController.

HappinessViewController.m

-(void)setHappiness:(int)happiness
{
    _happiness = happiness;
    NSString* result = [NSString stringWithFormat:@"%d", happiness];
    NSLog(@"Got happy %@", result);
    self.display.text = result; 
}

Now there’s one bug I haven’t been able to figure out yet. Which is how to refresh the view once it gets set here.

The self.display label is nil but once I figure it out I will come back up here and update.

For a much better walk through of who segues work check out Paul Hegarty’s Lecture 6 as part of the Stanford iPhone class series.

About these ads