Search code examples
ios7gestureback

How to disable back gesture in iOS 7 for only one view


I am trying to disable the back gesture for my view controller using the following set of code.

In FirstViewController.m, I'm setting the delegate of interactivePopGestureRecognizer

- (void) viewWillLoad {

    // Other stuff..
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
}

And then implementing the <UIGestureRecognizerDelegate> method and returning NO.

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {

     return NO;
}

And in dealloc I'm setting the delegate to nil. (I have read somewhere that in iOS 7, you have to manually set the delegates to nil)

- (void)dealloc {

    self.navigationController.delegate = nil;
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
}

This works in the FirstViewController. But when I push SecondViewController to this, the gesture does not work on that either. How can I disable the gesture in FirstViewController only?

Also when I pop FirstViewController to go to RootViewController and then try to push FirstViewController again, I get the object deallocated error :

[FirstViewController gestureRecognizer:shouldReceiveTouch:]: message sent to deallocated instance 0x14ed0280

Why else do I need to do other than setting the delegates to nil? Or am I setting it in the wrong place?


Solution

  • Try the below untested code in your FirstViewController :

    -(void) viewWillAppear:(BOOL)animated 
    {
        [super viewWillAppear:animated];
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    
    -(void) viewWillDisappear:(BOOL)animated 
    {
        [super viewWillDisappear:animated];
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }