如何回到Objective-C中的上一个视图?

use*_*535 8 objective-c uinavigationcontroller ios

我是iOS编程的初学者,我想实现回到主视图的功能.

我使用这段代码:

-(IBAction)onclickhome:(id)sender
{

    [self.navigationController popViewControllerAnimated:YES];
}
Run Code Online (Sandbox Code Playgroud)

我在主页按钮单击事件中使用了navigationController,但它没有跳转到主屏幕.

您有任何适用于我的代码的建议和源代码吗?

Lor*_*o B 11

我不确定我理解你的问题.

你是什​​么意思

我在主页按钮单击事件中使用了navigationController,但它没有跳转到主屏幕

如果要弹出到根控制器,可以使用popToRootViewControllerAnimated.

[self.navigationController popToRootViewControllerAnimated:YES];
Run Code Online (Sandbox Code Playgroud)

来自Apple doc UINavigationController

popToRootViewControllerAnimated:

Pops all the view controllers on the stack except the root view controller and updates the display.
- (NSArray *)popToRootViewControllerAnimated:(BOOL)animated
Run Code Online (Sandbox Code Playgroud)

如果您已设置a UINavigationController并且其根控制器名为A,那么如果您从A导航到B然后从B导航到C,则有两种可能性可以返回到前一个控制器(您可以使用其他控制器,但我列出了主控制器) ):

  • 用C导航回C到B. popViewControllerAnimated
  • 用C导航回C到A. popToRootViewControllerAnimated


use*_*323 6

导航来回视图的最佳方法是从导航视图控制器堆栈中推送和弹出视图.

要返回一个视图,请使用下面的代码.这将确保保留视图之间的平滑过渡.

UINavigationController *navigationController = self.navigationController;
[navigationController popViewControllerAnimated:YES];
Run Code Online (Sandbox Code Playgroud)

要返回两个视图,请执行以下操作

UINavigationController *navigationController = self.navigationController;
[navigationController popViewControllerAnimated:NO];
[navigationController popViewControllerAnimated:YES];
Run Code Online (Sandbox Code Playgroud)

如果您没有回到预期的视图,请在弹出任何视图之前执行以下代码...

UINavigationController *navigationController = self.navigationController;
NSLog(@"Views in hierarchy: %@", [navigationController viewControllers]);
Run Code Online (Sandbox Code Playgroud)

你应该看到一个类似下面的数组,它将帮助你验证堆栈是否按预期维护.

Views in hierarchy: (
    "<Main_ViewController: 0x1769a3b0>",
    "<First_ViewController: 0x176a5610>",
    "<Second_ViewController: 0x176af180>"
Run Code Online (Sandbox Code Playgroud)