Search code examples
iosobjective-cuinavigationcontrolleruistoryboardsegue

Custom UIStoryboardSegue on back button press?


I've got a custom UIStoryboardSegue that 'zooms' a UIImageView. Now I also need a custom UIStoryboardSegue that 'zooms out' when a user presses the back button in the UINavigationController. I've been trying to do this for some days now, but without success.

I've subclassed UINavigationController and added the code below to it:

- (UIStoryboardSegue *)segueForUnwindingToViewController:(UIViewController *)toViewController fromViewController:(UIViewController *)fromViewController identifier:(NSString *)identifier {

    UIStoryboardSegue *theSegue;

    NSLog(@"Unwind called");

    if ([fromViewController isKindOfClass:[SetDetailViewController class]]) {
        theSegue = [ZoomOutSegue segueWithIdentifier:identifier source:fromViewController destination:toViewController performHandler:^(void){}];
    } else {
        theSegue = [super segueForUnwindingToViewController:toViewController fromViewController:fromViewController identifier:identifier];
    }

    return theSegue;
}

However, this isn't called. What am I doing wrong here?


Solution

    1. I'm assuming you are still switching views with your zooming
    2. I'm a Swiftie so my help will be in Swift

    You should be able to capture these events by making your class a delegate of your navigation controller and then using the willShowViewController method of your navigation controller

    • Add UINavigationControllerDelegate to your class when you define it
    • Under your viewDidLoad() function add self.navigationController?.delegate = self
    • Now you should be able to use a function that will run just before the navigation controller switches to a new view controller (so yes it will also run when the back button is pressed). In Swift it looks like this:

      func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
      
      //if the view controller we are going to is one we want to trigger this action
      if let _ = viewController as? ViewController {
          //perform the thing you want here
      }}