Adding same button to all view controllers in UINavigationController Adding same button to all view controllers in UINavigationController ios ios

Adding same button to all view controllers in UINavigationController

The navigation item is per view controller. The navigation bar draws its contents from the navigation item of the view controller whose view it's currently framing, which corresponds to the view controller at the top of the navigation controller's stack.

You basically need each view controller to stick a cancel button in its navigation item. You can do any of the following:

  • Copy-paste the code into all relevant view controllers.
  • Move the code into a utility function or class and call that.
  • Create a common superclass for all relevant view controllers that handles setting up the cancel button for its subclasses.

You can also subclass UINavigationcontroller and overide few methods like this:

- (id)initWithRootViewController:(UIViewController *)rootViewController {    self = [super initWithRootViewController:rootViewController];    if (self) {        [self setCloseButtonToController:rootViewController];    }    return self;}- (void)dismissController {    [self dismissViewControllerAnimated:YES completion:nil];}- (void)setCloseButtonToController:(UIViewController *)viewController {    UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithTitle:@"Close" style:UIBarButtonItemStylePlain target:self action:@selector(dismissController)];    [viewController.navigationItem setRightBarButtonItem:closeItem];}- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {    [super pushViewController:viewController animated:animated];    [self setCloseButtonToController:viewController];}

You can instead adopt the UINavigationControllerDelegate protocol in the class which creates the UINavigationController instance. You can also create the cancelButton in advance and then implement navigationController:willShowViewController:animated: like this,

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {    viewController.navigationItem.rightBarButtonItem = cancelButton;}

You will have to remember to create and hold the cancelButton and not release it. This will also mean cancelRequestNewLeave: will have to be a method in class that creates the UINavigationController instance which is what it is right now I guess.