【问题标题】:xcode issues when coming from another view controller来自另一个视图控制器时的 xcode 问题
【发布时间】:2014-03-01 20:25:45
【问题描述】:

我正在开发一个 iPhone 应用程序并遇到了一些问题。我有一个主视图控制器和另一个名为 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];
 }];

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

【问题讨论】:

    标签: ios iphone uiviewcontroller


    【解决方案1】:

    你有什么理由不使用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 将视图控制器显示在其堆栈的顶部。

    【讨论】:

    • 最好使用initWithRootViewController:,你有navigationControllers = 我猜你的意思是viewControllers = 。
    • @Wain 谢谢!我在考虑 UITabBarController ,其中更常见的是传递一组视图控制器。我更新了我的示例。
    【解决方案2】:

    您的“返回”代码并没有真正返回,而是返回然后呈现主视图控制器的新副本。

    然后,您的“游戏”代码将被解除,这将删除当前控制器(因为您在返回时呈现了它),然后从中呈现游戏。

    这很混乱,因为您将展示其展示控制器已被销毁的控制器。最好使用导航控制器。但是,如果您只是像这样呈现和关闭,则可以更正当前代码:

    首页 -> 游戏:

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

    游戏 -> 主页

    [self dismissViewControllerAnimated:YES completion:NULL];
    

    【讨论】:

    • 但我想重新加载视图。我怎么能做到这一点?
    • 视图控制器应该接收viewWillAppear:和viewDidAppear:方法回调,这样你就可以在那里更新你的UI。
    【解决方案3】:

    您应该寻找 Segues 代替!您无法关闭源视图控制器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多