以编程方式调用 iOS 上的导航控制器返回按钮

在一个基于 UINavigationController 的 iPhone 应用程序中,在一个方法中,我希望执行相当于按下后退按钮并返回视图的程序化等效操作。

例如,自动按下 Jobs 按钮,如下图所示:

Navigation Controller image

是否有一个通用的 iOS 调用,我可以做,或是需要更多的信息?

73996 次浏览

You should call

popViewControllerAnimated:

which is the opposite of adding view controllers with pushViewController:animated:

UINavigationController's -popViewControllerAnimated: method should do what you want:

[navigationController popViewControllerAnimated:YES];

Assuming you don't actually want to PRESS the button programmatically, but simply copy the outcome of pressing the button, you should tell the navigation controller to pop the current view controller.

[self.navigationController popViewControllerAnimated:YES];

This will remove it from the stack, and return you to the previous view controller.

[self.navigationController popViewControllerAnimates:YES];

is the best option but if you are nor on the same view controller class or your delegate changes before your back button method called then you can also try--

first you have to define back button---

UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle: @"anyTitleForBackButton" style: UIBarButtonItemStyleBordered target: nil action: @selector(backButtonTapped)];


[[self navigationItem] setBackBarButtonItem: newBackButton];


[newBackButton release];

and then in backButtonTapped method you can call--

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

Swift 3.0

Back to the root view

self.navigationController?.popToRootViewController(animated: true)

Back to the previous view

self.navigationController?.popViewController(animated: true)

Swift 2.3

Back to the root view

self.navigationController?.popToRootViewControllerAnimated(true)

Back to the previous view

self.navigationController?.popViewControllerAnimated(true)