Illep
Illep

Reputation: 16841

Going back when clicked the back button - Beginner

I have a UIViewCOntroller, and my code is as follows.

TviewController *tviewController = [[TviewController alloc]init];
    [self.navigationController pushViewController:tviewController animated:YES];

Now from TviewController i go to another viewCOntroller;

XviewController *xviewController = [[XviewController alloc]init];
    [self.navigationController pushViewController:xviewController animated:YES];

in this XviewController there is a button, when i click that button i need to move BACK to the TviewController How do i do this programatically ?

note: I don't want to use pushViewController and push it further. I need to go back to the TviewController (as in clicking the back button twice)

Upvotes: 1

Views: 214

Answers (3)

HelmiB
HelmiB

Reputation: 12333

there is 3 possible ways.

  1. use popToRootViewControllerAnimated: -> to go back root view controller (first view controller)

  2. use popViewControllerAnimated: -> to go backward 1. it's exact same way as back button.

  3. use popToViewController:animated: -> to go back to UIViewController you want (as long as it's stack at back).

point 1 & 2 is pretty easy to implement and other answers lead you to there.

for point 3, here it is:

@class TviewController.h;
@interface XviewController : UIViewController
{
//this is XviewController.h
//you may use `#import` other than use `@class` but on some reason you can't, if you use`#import XviewController.h` in your TviewController class.
}

//XviewController.m
#import TviewController.h
#import XviewController.h
@implementation

-(IBAction) backTviewController
{
   for ( UIViewController *viewController in self.navigationController.viewControllers ) 
      if ( [viewController isMemberOfClass:[TviewController class]]{
        [self.navigationController popToViewController:viewController animated:YES];
        break;
      } 
}

Upvotes: 1

Shubhank
Shubhank

Reputation: 21805

[self.navigationController popViewControllerAnimated:BOOL)]
    [self.navigationController popToViewController:(UIViewController *) animated:(BOOL)];

        [self.navigationController popToRootViewControllerAnimated:(BOOL)];

are methods to go back in hierarchy

Upvotes: 3

Manlio
Manlio

Reputation: 10865

Just

[self.navigationController popViewControllerAnimated:YES];

You should spend some time reading the guidelines about view controllers...

Upvotes: 3

Related Questions