Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

ios - How can I remove a view from navigation controller

I want to call a new view controller and remove the current view controller from the navigation controller stack. For example. I am in view controller A and I call B.

Now I have in the stack A , B. Now I want to call C (from B). I want the stack to be A, C.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the context of ARC, here's a possible solution:

NSMutableArray* navArray = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];
[navArray replaceObjectAtIndex:[navArray count]-1 withObject:nextViewController];
[self.navigationController setViewControllers:navArray animated:YES];

As you can tell, this code replaces the usual push code in the view you're trying to remove from stack ("B," in your question). Line 1 copies the list of view controllers from the nav-controller stack into an NSMutableArray. Line 2 replaces the last (topmost) view with the view we want to go to next ("C"). Line 3 makes the actual nav-controller's stack to be our altered array, and animates the transition to the topmost item. (Of course you can't use this code in the root viewController.)

I found an alternative way here and adapted it for ARC:

UINavigationController *navController = self.navigationController;
[navController popViewControllerAnimated:NO];
[navController pushViewController:someViewController animated:YES];

The first line is needed because once you've popped the current view off the stack, self.navigationController will be nil and the third line won't work. Same number of lines as the previous way, but this way works through built-in methods instead of "manually" fiddling with the stack.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...