我正在开发一个iPhone应用程序,遇到了一些问题。我有一个主视图控制器和另一个称为GameViewController的控制器。我在主视图控制器中有一个按钮可以转到游戏,在游戏中有一个后退按钮可以返回主视图控制器。如果我转到游戏视图控制器并返回主控制器,下次我按下按钮转到游戏视图控制器时,我会发现各种故障。这是我的按钮转到游戏视图控制器的代码:
GameViewController *game = [[GameViewController alloc] initWithNibName:nil bundle:Nil];
[self dismissViewControllerAnimated:YES completion:NULL];
[self presentViewController:game animated:YES completion:NULL];
以下是转到主视图控制器的后退按钮代码:
ViewController *home = [[ViewController alloc] initWithNibName:nil bundle:nil];
UIViewController *parentViewController = self.presentingViewController;
[self dismissViewControllerAnimated:YES completion:^
{
[parentViewController presentViewController:home animated:NO completion:nil];
}];
如果有人能帮忙,将不胜感激。
你不使用UINavigationController
有什么原因吗?即使您想要隐藏导航栏并提供自己的导航 UI,也可以使用它。听起来你有自己的后退按钮,这就足够了。
使用 UINavigationController,您的代码将更像这样:
// in your application delegate's application:didFinishLaunchingWithOptions: method
UINavigationController *nav = [UINavigationController alloc] initWithRootViewController:home];
nav.navigationBarHidden = YES; // this hides the nav bar
self.window.rootViewController = nav;
// from your 'home' VC to present the game vc:
GameViewController *game = [[GameViewController alloc] initWithNibName:nil bundle:Nil];
[self.navigationController pushViewController:game animated:YES];
// from your 'game' VC to get back to 'home':
[self.navigationController popViewControllerAnimated:YES];
你只在一个地方实例化"主"和"游戏"视图控制器,UINavigationController 在其堆栈的顶部显示视图控制器。
你"返回"的代码并没有真正返回,而是返回,然后呈现主视图控制器的新副本。
然后,您的"游戏"代码被关闭,这将删除当前控制器(因为您在返回时出示了它),然后从中呈现游戏。
这很混乱,因为您将看到其呈现控制器已被销毁的控制器。您最好使用导航控制器。但是,如果您只是显示和关闭,则可以更正当前代码:
首页 -> 游戏:
GameViewController *game = [[GameViewController alloc] initWithNibName:nil bundle:Nil];
[self presentViewController:game animated:YES completion:NULL];
游戏 ->主场
[self dismissViewControllerAnimated:YES completion:NULL];
你应该寻找Segues!您无法关闭源查看器。