Simple storyboard setup: UIViewController with UINavigationController. On a table cell click a custom segue pushes a new UIViewController onto the navigation stack. All good. But then pressing the "back" button in the navigation bar, it only uses the default pop animation.
How do I tell the navigation controller to use my custom segue when popping back? I've added
- (UIStoryboardSegue *)segueForUnwindingToViewController:(UIViewController *)toViewController fromViewController:(UIViewController *)fromViewController identifier:(NSString *)identifier
- (BOOL)canPerformUnwindSegueAction:(SEL)action fromViewController:(UIViewController *)fromViewController withSender:(id)sender
to both view controllers but they don't get called at all.
What am I missing?
You can accomplish this by creating a custom transition instead of using a custom segue. It took me a while to understand, but it is basically very simple. Just make sure that your first view controller adopts the UINavigationControllerDelegate protocol. Then, still in the first view controller, implement the following method:
- (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
animationControllerForOperation:(UINavigationControllerOperation)operation
fromViewController:(UIViewController *)fromVC
toViewController:(UIViewController *)toVC
{
return X // where X is an animation Controller object, an instance of the animator class.
}
Still in the first view controller, for example in ViewDidLoad, tell the navigationcontroller that the first view controller will act as its delegate:
self.navigationController.delegate = self;
Last but not least, create an animator class that adopts the UIViewControllerAnimatedTransitioning protocol. Implement the following methods:
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
and
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
The first method holds the transition code. This transition code will automatically be used when tapped on the back button.
Here is a very simple example project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With