ios - 以编程方式创建导航 Controller 时黑屏

标签 ios objective-c uinavigationcontroller

我正在以编程方式创建导航 Controller ,如下所示:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.mainMenuViewController = [[MainMenuViewController alloc] init];
    self.window.rootViewController = self.mainMenuViewController;
    UINavigationController* navigationController = [[UINavigationController alloc] initWithRootViewController:self.window.rootViewController];
    [self.window makeKeyAndVisible];
    [[GKHelper sharedInstance] authenticateLocalPlayer];
    return YES;
}

而且,虽然 Xcode 似乎对此非常满意,但当我使用此代码启动我的应用程序时出现黑屏。当我将其注释掉并仅使用 Storyboard 中的箭头时,它工作正常但我没有导航 Controller 。我做错了什么?

最佳答案

在尝试向其发送消息之前,您需要创建 UIWindow 对象。您还需要将导航 Controller 设置为窗口的 rootViewController

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.mainMenuViewController = [[MainMenuViewController alloc] init];
    UINavigationController* navigationController = [[UINavigationController alloc] initWithRootViewController:self.mainMenuViewController];
    self.window.rootViewController = navigationController;
    [self.window makeKeyAndVisible];
    [[GKHelper sharedInstance] authenticateLocalPlayer];
    return YES;
}

更新

我看到您正在尝试从使用 Storyboard过渡。您的 MainMenuViewController 需要以某种方式创建或加载其 View 。当您使用 Storyboard时,您的 MainMenuViewController 正在从 Storyboard加载其 View 。您有三个选择:

  1. 您可以从 Storyboard 中加载 MainMenuViewController,以便它从 Storyboard 中加载其 View 。在 Storyboard中,为您的 MainMenuViewController 提供一个标识符。假设您将标识符设置为 MainMenu。然后你可以像这样从 Storyboard 中加载 MainMenuViewController:

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    self.mainMenuViewController = [storyboard instantiateViewControllerWithIdentifier:@"MainMenu"];
    
  2. 您可以创建一个包含MainMenuViewController View 的.xib 文件。如果您将其命名为 MainMenuViewController.xibMainMenuViewController 将自动使用它(当您未从 Storyboard加载 View Controller 时)。

  3. 您可以实现 -[MainMenuViewController loadView] 来创建 View 并将其存储在 self.view 中。

关于ios - 以编程方式创建导航 Controller 时黑屏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16888626/

相关文章:

ios - 隐藏导航栏时出现奇怪的动画

ios - 在生产中完全禁用来自 XCGLogger 的日志

objective-c - 使用 Storyboard 从任何 View 执行到初始 View 的转换

ios - 提高 Tesseract OCR 质量失败

iphone - 同时加载行和整个表时崩溃

ios - 如果我使用 UINavigationController,内容不会旋转

swift - Segue "show detail"在 iOS 7 中不起作用 - Swift

ios - Swift iOS - 使用 CATransform3D .m34 属性更改 Swift 中的视角时,对变换应用额外的更改

ios - SFSafariViewController 崩溃 : The specified URL has an unsupported scheme

ios - 为什么在针对模拟器时框架包路径解析为 DerivedData 构建目录?