Search code examples
swiftuinavigationbar

Is there any way to add a completion function to the navigation bar's back button?


I was wondering if there was any way to add a handler or completion function to after the back button in the navigation bar is pressed to hide the navigation bar itself.


Solution

  • For this purpose, you should implement the custom back button

    override func viewDidLoad {
            super.viewDidLoad()
            self.navigationItem.hidesBackButton = true
            let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Bordered, target: self, action: "back:")
            self.navigationItem.leftBarButtonItem = newBackButton
        }
    
        func back(sender: UIBarButtonItem) {
            // Perform your custom actions
            // ...
            // Go back to the previous ViewController
            self.navigationController?.popViewControllerAnimated(true)
        }
    

    Or just simply write your code in viewWillDisappear method when you want the controller to disappear