Storyboard Custom Segue For Custom PushViewController Animation

While there are a lot of google hits when searching for custom pushViewController Animation, I found nothing regarding use of a Custom Segue to make it reusable and I also found a lot of misinformation like “it can’t be done with the default UINavigationController.” It can.

From your Button, View, Gesture Recognizer or whatever, instead of dragging from Push, drag from Custom.

Then select the Segue that is created and type in a class name the custom Segue.

Now we can create the FromTopReplaceSegue class. Use Add File or however you like to create new classes in XCode.

//FromTypeReplaceSegue.h

#import <UIKit/UIKit.h>
@interface FromTopReplaceSegue : UIStoryboardSegue
@end

//FromTypeReplaceSegue.m

#import “FromTopReplaceSegue.h”
@implementation FromTopReplaceSegue
-(void)perform{
UIViewController *dst = [self destinationViewController];
UIViewController *src = [self sourceViewController];
[dst viewWillAppear:NO];
[dst viewDidAppear:NO];

[src retain];

[src.view addSubview:dst.view];

CGRect original = dst.view.frame;

dst.view.frame = CGRectMake(dst.view.frame.origin.x, 0-dst.view.frame.size.height, dst.view.frame.size.width, dst.view.frame.size.height);

[UIView beginAnimations:nil context:nil];
dst.view.frame = CGRectMake(original.origin.x, original.origin.y, original.size.height, original.size.width);
[UIView commitAnimations];

[self performSelector:@selector(animationDone:) withObject:dst afterDelay:0.2f];
}
– (void)animationDone:(id)vc{
UIViewController *dst = (UIViewController*)vc;
UINavigationController *nav = [[self sourceViewController] navigationController];
[nav popViewControllerAnimated:NO];
[nav pushViewController:dst animated:NO];
[[self sourceViewController] release];
}
@end

In this CustomSegue not only are we doing custom animation from Top to Bottom (just like the default push navigation of Right to Left) but instead of pushing, we are replacing the top view controller.

In my current project I have a nearly identical FromButtomReplaceSegue that does the replace but animates from Button. I hope for a library of these with varying animation transitions and Push/Replace variants of each. Then anytime you want to use a different animation you can simply use a Custom Segue instead of writing a bunch of code in ViewDidLoad or wherever. Hurray Storyboard!

  1. http://stackoverflow.com/questions/2215672/how-to-change-the-push-and-pop-animations-in-a-navigation-based-app
  2. http://stackoverflow.com/questions/5878732/how-to-create-uinavigationcontroller-animation-top-to-bottom
  3. http://dmunsie.wordpress.com/2009/08/07/custom-animations-between-uiviewcontrollers/