Search code examples
iosuinavigationcontrolleruinavigationbaruibarbuttonitemuinavigationitem

have a universal bar button item in navigationController


I Have UINavigationController in my app, I want to have a right UIBarButtonItem to be shown in all navigation bar that appear in my application. this button will load menu, so I don't want to add this button in every navigation bar manually, also as the function is loading menu, I don't want to copy/past action for this button.

is there any way to handle this in ViewController.h and .m ?

so the button act as a universal bar button item?


Solution

  • What you can do is subclass the navigation controller. Here is an example

    @interface NavigationController : UINavigationController
    @end
    
    @interface NavigationController () <UINavigationBarDelegate>
    @end
    
    @implementation NavigationController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        for (UIViewController* viewController in self.viewControllers){
            // You need to do this because the push is not called if you created this controller as part of the storyboard
            [self addButton:viewController.navigationItem];         
        }
    }
    
    -(void) pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
        [self addButton:viewController.navigationItem];
        [super pushViewController:viewController animated:animated];
    }
    
    -(void) addButton:(UINavigationItem *)item{
        if (item.rightBarButtonItem == nil){
            item.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(action:)];
        }
    }
    
    -(void) action:(UIBarButtonItem*) button{
    
    }
    
    @end