How to customize the action of backBarButtonItem in Swift (iOS 14.4)

137 views Asked by At

My application has one UINavigationController as the initial view controller, and RootViewControler as the root view controller for UINavigationController.

Then I created FirstViewController and SecondViewController, so we can navigate from RootViewController, to FirstViewController and then SecondViewController.

The question comes on how to customize the action of the backBarButtonItem on the navigation bar. The default backButtonItem pops out the top view controller but I would like to show some alert before pop up.

I tried to add following code in viewDidLoad for RootViewController, FirstViewController and SecondViewController, but I am still having the default behavior for back button.

override func viewDidLoad() {
    super.viewDidLoad()
    
    navigationItem.backBarButtonItem = UIBarButtonItem(title: "Hello", style: .plain, target: self, action: #selector(backButtonTapped))
}

Wonder do I miss something?

Thanks.

1

There are 1 answers

0
matt On

You cannot customize the action of a back bar button item. It does just one thing: go back. If you want to write your own button that does something else, use a left bar button item (and possibly suppress the back bar button item).