Programmatically calling a Segue

In storyboarding in Xcode, you can create your segues very easily with CTRL-DragDrop in the Interface Builder. But I encourage you to always name your Segues. You will thank yourself later.

Here’s how you could use that named Segue later.

1. In the Identifier field for the new Segue you just created, give it a name. Remember, in objective-c, we like really descriptive and (hence) long names. Don’t shy away from longer names as you normally would in some other languages.

In this case, let’s say we have a Segue named SegueSplashPageToLogin.

2. We can call it directly causing the Segue to be executed.

[self performSegueWithIdentifier:@"SegueSplashPageToLogin" sender:self];

3. Where it comes in really handy though is checking something after a Segue is called.
This method prepareForSegue is something you can declare and your app’s prepareForSegue method will be called just after the Segue is called, but before the controller actually pans to the next view.

For instance, here is a method that checks to see which segue was called. It uses that information to determine whether you are the owner of something or simply a participant. In doing so, it knows which controller to load. This is made up, but you get the idea.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"SegueHomeToOwnerDetail"]) {
        NSLog(@"prepareForSegue called for SegueHomeToOwnerDetail");
        NSIndexPath *selectedRowIndex = [self.tableView indexPathForSelectedRow];
        OwnerViewController *ownerViewController = [segue destinationViewController];
        ownerViewController.myObject = [_activeArray objectAtIndex:selectedRowIndex.row];
    } else {
        NSLog(@"prepareForSegue called for SegueHomeToParticipantDetail");
        NSIndexPath *selectedRowIndex = [self.tableView indexPathForSelectedRow];
        ParticipantViewController *participantViewController = [segue destinationViewController];
        participantViewController.myObject = [_activeArray objectAtIndex:selectedRowIndex.row];
    }
}
Advertisements
Previous Post
Leave a comment

3 Comments

  1. I was searching for a way to push Segues programmatically – this helped. Thanks!

    Reply
    • Hey that’s great! Thanks for letting me know, I appreciate the feedback. Good luck with your work, let us all know when you’re finished!

      Reply
  1. Programmatically calling a Segue | tediscript.wordpress.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: