“Cancel” button (UIBarButtonItem) not working in iOS view controller


This Content is from Stack Overflow. Question asked by Piyush Khanna

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:

    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?



Check the Answers

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?