Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set common Bar Button Item on Navigation Bar

I want to set the common Bar Button Item on the right of the Navigation Bar, it should be display on all screens managed by Navigation Controller and it calls the same action.

Just for example, in Master Detail Application template, there is "addButton" on the right of the Navigation Bar, I want to display it on DetailViewController as well (it won't be work because action is missing though).

I have created a subclass of UINavigationController, in which I can change something like Navigation Bar color, but I can't set Bar Button Items. I can set Bar Button Items in each screen's ViewController so that I have to duplicate action for each screen.

Also I've tried to create a subclass of UINavigationBar, but I don't know if I can add Bar Button Item on it.

How to set common Bar Button Item on Navigation Bar?

Thanks in advance.

like image 676
5t111111 Avatar asked Jan 05 '15 03:01

5t111111


2 Answers

Another easy way to do instead of creating an extension

implement UINavigationControllerDelegate in root view controller

func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
    let backBarButton = UIBarButtonItem.init(title: "HINIBO", style: .Plain, target: self, action: Selector("menuButtonAction:"))
    viewController.navigationItem.rightBarButtonItem = backBarButton
}
like image 57
mdkr Avatar answered Oct 07 '22 04:10

mdkr


You can use category to approach it. Let's say UIViewController+NavigationBar category

1.Create a category

2.Add a method, -(void)setNavigationBarItem method (in this case) in .h file.

3.implement the method in .m file to deal with the set Bar Button Items stuff.

- (void)setNavigationBarItem
{
  UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(something)];
  self.navigationItem.rightBarButtonItem = searchItem;
}

4.In which viewController you want the NavigationBarItem, import the category header and call [self setNavigationBarItem] method.

like image 30
Zigii Wong Avatar answered Oct 07 '22 05:10

Zigii Wong