How to set a common bar element in the navigation bar

I want to set the general "Button Bar" element to the right of the navigation bar, it should be displayed on all screens controlled by the navigation controller, and it will trigger the same action.

It’s easy, for example, in the application template "Detail Wizard" there is an "addButton" to the right of the navigation bar, I also want to display it on the DetailViewController (this will not work because there is no action).

I created a subclass of UINavigationController in which I can change something like color in the navigation bar, but I cannot set Button elements. I can set toolbar elements on each ViewController screen so that I have to duplicate the action for each screen.

I also tried to subclass UINavigationBar, but I don't know if I can add a Button Bar element to it.

How to set a common bar element in the navigation bar?

Thanks in advance.

+5
source share
2 answers

You can use a category to get closer to it. Say UIViewController+NavigationBar category

1.Create a category

2. Add the -(void)setNavigationBarItem (in this case) to the .h file.

3.Use the method in the .m file to deal with the contents of the toolbar items.

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

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

+4
source

Another easy way to do this instead of creating an extension

implement UINavigationControllerDelegate in the 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 } 
+4
source

Source: https://habr.com/ru/post/1210378/


All Articles