加载之前在 iOS 中加载的视图

Load a view that is previously loaded in iOS

我一直在搜索这个问题,但还没有得到任何答案。我的问题是:我有一个按钮,单击它会推送到另一个视图。

我是这样推送的:

ViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]
                      instantiateViewControllerWithIdentifier:@"Main_View"];
[self.navigationController pushViewController:vc animated:YES];

ViewControllervc是我推的观点。所以在新视图中,有一个后退按钮,可以放下当前视图,回到旧视图。当我单击按钮时,vc 已从所有位置再次加载。

如何让vc的实例留在内存中,这样当我回到旧视图再次来到vc时,不需要重新加载? 我想这与 navigationController 堆栈有关,但不知道该怎么做。 谢谢

只需在您的第一个 ViewController

中保留一个 ViewController 实例作为 属性
@property (strong,nonatomic)ViewController * vc;

然后push的时候检查是否在内存中

 if (self.vc == nil) {
    self.vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]
                                 instantiateViewControllerWithIdentifier:@"Main_View"];
}
[self.navigationController pushViewController:self.vc animated:YES];

您使用的是 UINavigationController 吗?如果是这样,可以在您的后退按钮中调用以下代码行 'IBAction':

[self.navigationController popViewControllerAnimated:YES];

如果您确实需要保留视图控制器的实例,请按照 Leo 的建议进行操作。