UINavigationController Category Pop Gesture with Custom Back Button

1.2k views Asked by At

I use a custom back button in tons of places in an app I'm working on, so I have a category on UINavigationController that adds a pushViewControllerWithBackArrow method that sets a custom back arrow on the view controller being pushed, then pushes it. However, I can't seem to get the interactivePopGestureRecognizer working. The code I've found here on stack overflow and online all either subclass UINavigationController or set the interactivePopGestureRecognizer in the pushed view controller.

One solution (http://keighl.com/post/ios7-interactive-pop-gesture-custom-back-button/) involved adding this code to viewDidLoad in the UINavigationController subclass:

__weak UINavigationController *weakSelf = self;

if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)])
{
    self.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)weakSelf;
}

which was semi-functional, but if I swiped back when in my root view controller it locked up the UI. The solution to this problem involved subclassing UINavigationController and overriding pushViewController and didShowViewController, which I would like to avoid.

Is there any way to make the gesture recognizer work on a UINavigationController category?

1

There are 1 answers

1
guest On

The best solution is to create a category for a UIViewController so that you could use this throughout your project as shown below. You can also just copy the code for the method customizeBackButton and put it in whatever view controller you need

//UIViewController+Back.h
#import <UIKit/UIKit.h>

@interface UIViewController (Back)

- (void)customizeBackButton;


@end

implement this method

//UIViewController+Back.m
#import "UIViewController+Back.h"

@implementation UIViewController (BackButton)
- (void)customizeBackButton
{
    UIImage *backButtonImage = [UIImage imageNamed:@"back.png"];
    UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithImage:backButtonImage style:UIBarButtonItemStylePlain target:self.navigationController action:@selector(popViewControllerAnimated:)];
    self.navigationItem.hidesBackButton = YES;
    [self.navigationItem setLeftBarButtonItem: customItem];
}
@end

Please note that you have to hide the original back button with self.navigation.hidesBackButton or else they'll both show up. Then, use it in wherever you need it!

-(void) viewWillAppear:(BOOL)animated {
    [self customizeBackButton];
}