In this recipe, we will learn how we can use the storyboard features to transition to another view controller through code.
In this section, we will look at how we can programmatically transition to another view controller through the use of segues.
In order to programmatically perform a transition to another view controller using a segue, perform the following simple steps:
MainStoryboard.storyboard
file from the project navigator.secondViewController
.Next, we need to modify our view controller to include the prepareForSegue:sender
method that will be responsible for handling transitions between view controllers within the storyboard:
ViewController.m
implementation file from the project navigator.prepareForSegue:sender
method, as shown in the following code snippet:-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Ensure we are processing the correct segue within the // Storyboard. if ([segue.identifier isEqualToString:@"secondViewController"]) { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Twitter Example" message:@"Currently displaying View #2" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alertView show]; } }
When the compilation completes, the iOS Simulator will appear; click on the About Twitter App button to see the transition happen to the second view controller.
Whenever a user triggers a segue in the current scene, the storyboard runtime calls the prepareForSegue:sender
method for the current view controller. This method gives the current view controller an opportunity to pass any needed data to the view controller that is about to be displayed.
Next, we perform a segue call associated with a control using its identifier, which we created, and check to ensure that we are processing the correct segue, before displaying an alert when the view is displayed.
Handling it this way allows us to customize segues, and applies any transition to the scene that is located within your storyboard, as long as the identifier is unique.
For information on how to implement the methods of the UIViewController
class, refer to the Apple Developer documentation, located at https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/cl/UIViewController
.