Search code examples
iosswiftuinavigationcontrolleruitabbarcontroller

Bar button for all tab bar controllers


I have three view controllers embedded in UITabBarController. Each view controller is embedded in navigation controller.

The logic of my app is to have navigation right bar button on all tab bar view controllers (i.e. "Menu" button which should be seen from each view controller). The easiest way to achieve this is to add this button to all navigation controllers separately. But I think it is not good solution because then the code for this button must be repeated in each navigation controller.

Is there any way to have same navigation right button on all controllers of UITabBarController?

(In my app i'm not using Storyboards)


Solution

  • extension UIViewController create a navigation bar Method call anywhere from ViewController in your project.navigation bar will appear with right button menu .

    for example

        import UIKit
    
        extension UIViewController {
    
            func setupNavigationBar(title: String) {
                // back button without title
                //self.navigationController?.navigationBar.topItem?.title = ""
    
                //back button color
                //self.navigationController?.navigationBar.tintColor = UIColor.white
    
                //set titile
                 self.navigationItem.title =  title
    
                //set text color & font size
                //self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.init(red: 251/255, green: 251/255, blue: 251/255, alpha: 1) , NSFontAttributeName:UIFont.systemFont(ofSize: 19)]
    
                //set background color without gradian effect
                //self.navigationController?.navigationBar.barTintColor = UIColor.init(red: 134/255, green: 145/255, blue: 152/255, alpha: 1)
    
                //show right button 
                let rightButton = UIBarButtonItem(image: #imageLiteral(resourceName: "Menu"), style: .plain, target: self, action: #selector(menu))
    
                //right Bar Button Item tint color 
                //self.navigationItem.rightBarButtonItem?.tintColor = UIColor.init(red: 219/255, green: 219/255, blue: 219/255, alpha: 1)
    
                //show the Menu button item
                self.navigationItem.rightBarButtonItem = rightButton
    
                //show bar button item tint color 
                //self.navigationItem.rightBarButtonItem?.tintColor = UIColor.init(red: 219/255, green: 219/255, blue: 219/255, alpha: 1)
    
            }
    
            func menu(){ 
                print("showSlideOutMane fire ")
            }
    
        }