Creating Custom Segues

Interface Builder provides segues for all of the standard ways to transition from one view controller to another—from presenting a view controller to displaying a controller in a popover. However, if one of those segues doesn’t do what you want, you can create a custom segue.

The Life Cycle of a Segue

To understand how custom segues work, you need to understand the life cycle of a segue object. Segue objects are instances of UIStoryboardSegue or one of its subclasses. Your app never creates segue objects directly; they are always created on your behalf by iOS when a segue is triggered. Here’s what happens:

  1. The destination controller is created and initialized.

  2. The segue object is created and its initWithIdentifier:source:destination: method is called. The identifier is the unique string you provided for the segue in Interface Builder, and the two other parameters represent the two controller objects in the transition.

  3. The source view controller’s prepareForSegue:sender: method is called. See “Configuring the Destination Controller When a Segue is Triggered.”

  4. The segue object’s perform method is called. This method performs a transition to bring the destination view controller on-screen.

  5. The reference to the segue object is released, causing it to be deallocated.

Implementing a Custom Segue

To implement a custom segue, you subclass UIStoryboardSegue and implement the two methods described earlier:

“Creating Custom Segues” shows a very simple custom segue. This example simply presents the destination view controller without any sort of animation, but you can extend this idea with your own animations as necessary.

Listing 13-1  A custom segue

- (void)perform
{
// Add your own animation code here.
 
    [[self sourceViewController] presentModalViewController:[self destinationViewController] animated:NO];
}