来自另一个视图控制器的xcode问题

我正在开发一个iPhone应用程序并遇到了一些问题。 我有一个主视图控制器和另一个名为GameViewController。 我在主视图控制器中有一个按钮可以进入游戏,然后在游戏中返回一个按钮返回主视图控制器。 如果我去游戏视图控制器并返回主,下次我按下按钮转到gameviewcontroller,我发现各种故障。 这是我转到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]; }]; 

如果有人可以提供帮助,将不胜感激。

你’回’的代码并没有真正回归,它会回来然后呈现一个新的家庭视图控制器副本。

然后,你的’游戏’代码将被解雇,这将删除当前的控制器(因为你在回去时呈现它),然后从中呈现游戏。

这很乱,因为你会看到控制器的控制器被破坏了。 你最好使用导航控制器。 但是,如果您只是出现并解雇,您可以更正当前的代码:

主页 – >游戏:

 GameViewController *game = [[GameViewController alloc] initWithNibName:nil bundle:Nil]; [self presentViewController:game animated:YES completion:NULL]; 

游戏 – >家

 [self dismissViewControllerAnimated:YES completion:NULL]; 

有没有理由不使用UINavigationController ? 即使您想隐藏导航栏并提供自己的导航UI,也可以使用此function。 听起来你有自己的后退按钮,这就足够了。

使用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在其堆栈顶部显示视图控制器。

你应该寻找Segues! 您无法关闭源viewcontroler。