iphone NavigationController clear views stack

喜夏-厌秋 提交于 2019-12-05 19:03:00
The Kraken

The following code will allow the user to drill down a view hierarchy, and at the press of a button, pop back to the root view controller and push a new view.

DetailViewController.m ~ the view controller from which to clear the navigation stack:

- (IBAction)buttonPressed:(id)sender {
    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"popBack" object:nil]];
}

The above code makes a call to NSNotificationCenter, posting a notification that the RootViewController can react to when heard. But first, the RootViewController must register to receive the notification.

RootViewController.m

- (void)viewDidLoad
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushViews) name:@"popBack" object:nil];
    [super viewDidLoad];
}

Next, the RootViewController must set up the referenced selector -pushViews.

- (void)pushViews {
     //Pop back to the root view controller
     [self.navigationController popToRootViewControllerAnimated:NO];

     //Allocate and init the new view controller to push to
     NewViewController *newVC = [[NewViewController alloc] init];

     //Push the new view controller
     [self.navigationController pushViewController:newVC animated:YES];
}

Be sure that when you call -popToRootViewControllerAnimated:, you specify NO for animation. Enabling animation causes hiccups in the navigation bar animation and confuses the system. The above code, when called, will clear the navigation stack, leaving only the RootViewController, and then adding the NewViewController.

The reason your initial code was not fully executing was because after calling -popToRootViewController: from your DetailViewController, the RootViewController's methods occupied the main thread, and the DetailViewController was released. Thus, no further code was run from that view controller. Using the code above, the navigation stack is popping back to the same view controller that is being loaded.

I think you're looking for -popToRootViewControllerAnimated:

UIViewController* root = [self.navigationController.viewControllers objectAtIndex:0];

self.navigationController.viewControllers = [NSArray arrayWithObjects:root, cal, nil];

Where 'cal' view controller to go. But there is no animation.

Vinay

In addition to The Kraken answer,

Add below function in UIViewController, which you are going to pop.

(void)viewDidDisappear:(BOOL)animated {

    [super viewDidDisappear:YES];

    for(UIView *view in self.view.subviews)
    {
       [view removeFromSuperview];
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!