Search code examples
iosswiftuinavigationcontrolleruinavigationbar

Button in navigation bar


How do I add a button to navigation bar that appears only in a particular view controller? And also how to add different buttons to different view controller that is embedded in navigation controller.


Solution

  • You don't have to add buttons to navigation bar, rather you could add bar button items. If you want you can customise bar button item to meet your requirements like setting a custom image as suggested by @Pushpendra.

    Programatically: Your View Controller is responsible for providing bar button item(s) for it's navigation bar. Create bar button items inside each of your view controller's viewDidLoad() or in init() if you have overridden it.

    Storyboards: It's pretty handy to drag n drop bar button items from storyboard editor and have the outlets setup so that you can change the behaviour later.

    If you are precisely looking to control the behaviour, then you can add or remove a bar button as and when needed depending on your conditional requirements.

    class FooViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
    
            /// Assuming this view controller presented/pushed with navigation controller
            let buttonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(FooViewController.buttonItemAction(sender:)))
            self.navigationItem.leftBarButtonItem = buttonItem
        }
    
        @IBAction func buttonItemAction(sender: UIBarButtonItem)    {
            /// some action
        }
    }
    
    
    class BarViewController: UIViewController {
        var buttonItem: UIBarButtonItem?
        var showButtonItem = false
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            /// Assuming this view controller presented/pushed with navigation controller
            buttonItem = UIBarButtonItem(barButtonSystemItem: .bookmarks, target: self, action: #selector(BarViewController.buttonItemAction(sender:)))
            self.navigationItem.leftBarButtonItem = buttonItem
        }
    
        @IBAction func buttonItemAction(sender: UIBarButtonItem)    {
            /// some action
        }
    
        @IBAction func toggleButtonItem(sender: UIButton)   {
            self.navigationItem.rightBarButtonItem = (self.showButtonItem == true) ? self.buttonItem : nil
        }
    }
    

    If this is what you are not looking for then update your question along with the code that you have tried.