iSD
iSD

Reputation: 103

How to navigate to some other View Controller when Navigation Controller back button is pressed?

I have a viewController in which, on the click of back button, I need to go to a specific viewController and call its method.So I created a barButton and added as a BACK button in navigation bar.When its selector is called I can see only see a black screen, nothing else.

Here how I am doing it.

In viewDidLoad

  //Back Button in navigation Bar.
UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(navigationBackButtonClicked:)];
self.navigationItem.leftBarButtonItem=newBackButton;

The selector below executes and shows a black screen.

  -(void)navigationBackButtonClicked:(UIBarButtonItem *)sender {
   SharedManager *sharedManagerObject = [SharedManager sharedInstance];

   NSString *source = sharedManagerObject.toCityString;
   NSString *destination =  sharedManagerObject.fromCityString;
   NSString *dateStr = sharedManagerObject.dateSelected_String;

   BusListViewController *buslist_VC = [self.storyboard instantiateViewControllerWithIdentifier:@"BusListViewController"];


   [buslist_VC getBusListForSource:source destination:destination date:dateStr];

   [self.navigationController popToViewController:buslist_VC animated:YES];

 }

Upvotes: 0

Views: 504

Answers (3)

mityaika07
mityaika07

Reputation: 653

You should use

NSArray *navStacks = self.navigationController.viewControllers;

select needed view controller and do

[self.navigationController popToViewController:selectedVC animated:YES];

Upvotes: 0

cdescours
cdescours

Reputation: 6012

You need to add your buslist_VC to the view hierarchy of your navigation controller before using [popToViewController:animated:]. This is used to display some viewcontrollers already in the stack of your navigation Controller.

Either way what you're asking might be a weird behaviour for your user but you can use :

[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 1] animated:NO];
[self.navigationController pushViewController:buslist_VC animated:NO];

Upvotes: 1

Onik IV
Onik IV

Reputation: 5047

You cann't back to a new ViewController, you can push a new ViewController, in your code change this:

[self.navigationController pushViewController:buslist_VC animated:YES];

But keep in mind, you are putting this new viewController inside the other (where you are created a newBackButton), and the default back button come back to this. If you want to come back to the root use this:

   [self.navigationController popToRootViewControllerAnimated:YES];

Or, now you can come back to any viewController on the navigation stack, this array:

   NSArray *navStacks = self.navigationController.viewControllers;

Using popToViewController: be sure is in the stack.

Upvotes: 0

Related Questions