简体   繁体   中英

"Cancel" button (UIBarButtonItem) not working in iOS view controller

I am trying to add a "Cancel" button in my viewcontroller's navigation bar programmatically. The sole purpose of the button is to dismiss the current viewcontroller and go back to the root viewcontroller. I am using the following Objective-C code to achieve this:

UIBarButtonItem* cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(onTapCancel:)];
self.controller.navigationItem.leftBarButtonItem = cancelBtn;
self.navigationController = [[UINavigationController alloc] initWithRootViewController:self.controller];
[self.navigationController setNavigationBarHidden:NO animated:YES];

Cancel button function:

-(void)onTapCancel:(UIBarButtonItem*)item{
    NSLog( @"Cancel button Tapped");
    UIViewController *rootViewController = [
      [[UIApplication sharedApplication] keyWindow] rootViewController];
    [rootViewController dismissViewControllerAnimated:YES completion:nil];
}

The onTapCancel function gets invoked without any issues when I just have a log line instead of the code to dismiss the current viewcontroller. But when the code to dismiss the viewcontroller is added (lines 2-4 in the onTapCancel function), the function stops getting invoked (I don't even see the "Cancel button Tapped" log line in the logs). What could be the possible reason for this?

Following code works (log line is printed everytime the cancel button is tapped) when used in onTapCancel function:

-(void)onTapCancel:(UIBarButtonItem*)item{
    NSLog( @"Cancel button Tapped");
}

Thanks!

After a closer look at your code I can see now that you try to dismiss a root controller of your application. It doesn't make any sense on it's own, because the root controller is not dismissible, you can only replace it. If the controller you are trying to dismiss is in a navigation controller stack, then popping to the root view controller should look like this:

- (void)onTapCancel:(UIBarButtonItem*)item {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

If you present the controller modally (and from the first snippet of code, I assume the controller is also wrapped with a navigation controller), then just dismiss it:

- (void)onTapCancel:(UIBarButtonItem*)item {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM