Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any callback for swipe back gesture in iOS?

Sometimes when user go back to the previous UIViewController, I want to do something.

If the user clicked the back button in UINavigationBar, I can capture the event.

But if they use the swipe back gesture to go back, I cannot respond to the change.

So is there any callback for swipe back gesture?

Currently I can only disable this kind of page in my app through

interactivePopGestureRecognizer.enabled = NO;
like image 370
xi.lin Avatar asked Aug 14 '15 08:08

xi.lin


2 Answers

The easiest way is to hook into the one that's already built into UINavigationController by doing something like this:

override func viewDidLoad() {
  super.viewDidLoad()
  navigationController?.interactivePopGestureRecognizer?.addTarget(self, action: #selector(MyViewController.handleBackswipe))
}
    
@objc private func handleBackswipe() {
    navigationController?.interactivePopGestureRecognizer?.removeTarget(self, action: #selector(MyViewController.handleBackswipe))
    // insert your custom code here
}

The remember to call removeTarget(_:action:) in your selector, otherwise it'll spam your selector until the gesture ends.

like image 62
jakehawken Avatar answered Oct 17 '22 03:10

jakehawken


Try this.It gives you some what better solution.

- (void)viewDidLoad {
    [super viewDidLoad];
    UIScreenEdgePanGestureRecognizer *gesture = (UIScreenEdgePanGestureRecognizer*)[self.navigationController.view.gestureRecognizers objectAtIndex:0];
        [gesture addTarget:self action:@selector(moved:)];
}

In Target method.

-(void)moved:(id)sender{    
    // do what you want

//finally remove the target
    [[self.navigationController.view.gestureRecognizers objectAtIndex:0] removeTarget:self action:@selector(moved:)];
}
like image 21
Vishnuvardhan Avatar answered Oct 17 '22 02:10

Vishnuvardhan