How to get a uinavigation bar back button to return to anthother view controller

浪子不回头ぞ 提交于 2019-12-30 11:37:12

问题


How would I go about having a UINavigation controller navigate not to the previous view but the view before that. Basically I would like it to jump back 2 places instead of the default one.

This is unconventional I'm sure, but I just need to do it for now.

 self.navigationItem.backBarButtonItem =
    [[[UIBarButtonItem alloc] initWithTitle:@"Back"
                                      style:UIBarButtonItemStyleBordered
                                     target:nil
                                     action:nil] autorelease];

thanks for any help.


回答1:


Set:

self.navigationItem.backBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(goBack)] autorelease];

then create a method -goBack

-(void)goBack
{
   UIViewController *ctrl = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 2];
   [self.navigationController popToViewController:ctrl animated:YES];
}



回答2:


self.navigationItem.backBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(youractonEvent:] autorelease];



回答3:


If you do not want to depend on array's index then you can do some thing like below :

MyController * aMyController = nil ;
for (int i=0; i<[[self.navigationController viewControllers] count]; i++) 
{
    NSLog(@"%@",[[self.navigationController viewControllers] objectAtIndex:i]);
    if ([[[self.navigationController viewControllers] objectAtIndex:i] isKindOfClass:[MyController class]]) 
    {
        aMyController = [[self.navigationController viewControllers] objectAtIndex:i];      
    }
}           
[self.navigationController popToViewController:aMyController animated:YES];



回答4:


If you have three view controllers in NavigationController and currently you are viewing 3rd view controller and if you want to jump to 1st viewcontroller.

Try this. This will navigate you twice back.

[self.navigationController popToViewController:[[self.navigationController viewControllers] objectAtIndex:0] animated:YES];

Set appropriate value instead of 0 in your case.




回答5:


Add a target to the button you added

then use the following code to go back more than 1 viewController

//Get the view controller that is 2 step behind
UIViewController *controller = [nav.viewControllers objectAtIndex:nav.viewControllers.count - 2];

//Go to that controller
[nav popToViewController:controller animated:YES];


来源:https://stackoverflow.com/questions/11136690/how-to-get-a-uinavigation-bar-back-button-to-return-to-anthother-view-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!