How to tell when back button is pressed in a UINav

2019-01-26 12:13发布

Is it possible to check when the back button is pressed in a UINavigationController stack? I've tried adding a action and target to self.navigationItem.backBarButtonItem to no avail.

Anyone have any solutions?

2条回答
对你真心纯属浪费
2楼-- · 2019-01-26 12:32

You can try my way:

Write in your ViewController:

UIBarButtonItem *backBt = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"imageNameOfBackButton"] style:UIBarButtonItemStyleBordered target:self action:@selector(backBt_touch:)];
self.navigationItem.leftBarButtonItem = backBt;

And action method:

- (void)backBt_touch:(id)sender {
  [self.navigationController popViewControllerAnimated:YES];
}

You have to take a photo of back button you want.

Animation of hiding back button when viewController is popped is not the same animation of iOS!

P/s: enter image description here I've get it from simulator. Hope it useful! :)

查看更多
我只想做你的唯一
3楼-- · 2019-01-26 12:46

One way to get at this would be to override viewWillDisappear in the UIViewController that is visible when the back button is pressed:

- (void)viewWillDisappear:(BOOL)animated {
    if (self.isMovingFromParentViewController) {
        // handle back button press
    }
}

Obviously this doesn't directly intercept the press on the back button itself, but it gives you a chance to perform logic at that time.

查看更多
登录 后发表回答