Override Back Button In Navigation Controller

Sonic Master picture Sonic Master · Aug 30, 2016 · Viewed 11.4k times · Source

I have storyboard with these flow. I am using SWRevealViewController to navigate to each navigation controller.

- Navigation Controller 1 --> View Controller Initial (Home) --> View Controller Target
- Navigation Controller 2 --> View Controller X --> View Controller Y --> View Controller Target
- Navigation Controller 3 --> View Controller M --> View Controller Target

From View Controller Target on each flow, I want to override its back button so it could back to View Controller Initial (Home) and release its object on memory.

Is there any possible way to do this? Any help would be appreciated. Thank you.

Answer

Nirav D picture Nirav D · Aug 30, 2016

First you need to replace your back button with custom Back BarButton with it selector.

self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .Done, target: self, action: #selector(self.backToInitial(_:)))

func backToInitial(sender: AnyObject) {
     self.navigationController?.popToRootViewControllerAnimated(true)
}

If you are running swift 3.0 then selector syntax is like this.

self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .Done, target: self, action: #selector(self.backToInitial(sender:)))

Edit: For SWRevealViewController try like this.

let revealController = self.revealViewController;
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("InitialViewController") as! InitialViewController
let navigationController = UINavigationController(rootViewController: vc)
revealController.pushFrontViewController(navigationController, animated:true)