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.
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With