Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override Back Button In Navigation Controller

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.

like image 415
Sonic Master Avatar asked Aug 30 '16 09:08

Sonic Master


People also ask

How do I hide the back button on my navigation?

Way 1: Touch “Settings” -> “Display” -> “Navigation bar” -> “Buttons” -> “Button layout”. Choose the pattern in “Hide navigation bar” -> When the app opens, the navigation bar will be automatically hidden and you can swipe up from the bottom corner of the screen to show it.

What is a navigation controller?

NavController manages app navigation within a NavHost . Apps will generally obtain a controller directly from a host, or by using one of the utility methods on the Navigation class rather than create a controller directly. Navigation flows and destinations are determined by the navigation graph owned by the controller.


1 Answers

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)
like image 86
Nirav D Avatar answered Sep 30 '22 14:09

Nirav D