如何在 Objective C 中以编程方式设置根视图控制器?

ios*_*ios 6 objective-c ios rootviewcontroller

我是 iOS 开发的新手,试图学习如何以编程方式创建和设置视图。

我正在尝试在 Obj-C 中快速声明

window?.rootViewController = UINavigationController(rootViewController : ViewController()) 
Run Code Online (Sandbox Code Playgroud)

项目:单视图应用程序。尝试链接默认创建的 ViewController.h

根据 Krunals 的回答,我更新了代码,但模拟器中未显示导航控制器

Cmd+单击控制器不会导航到 ViewController 文件

#import "AppDelegate.h"
#import "ViewController.h"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIScreen *screen=[[UIScreen alloc]init];
    UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    self.window.makeKeyAndVisible;




    ViewController *controller = [[ViewController alloc] init];



    window.rootViewController = [[UINavigationController alloc] initWithRootViewController:controller] ;
Run Code Online (Sandbox Code Playgroud)

Kru*_*nal 1

ViewController在添加(用作导航的根控制器)到导航控制器堆栈之前初始化视图控制器。

这是初始化简单视图控制器的示例代码

UIViewController *controller = [[UIViewController alloc] init];
Run Code Online (Sandbox Code Playgroud)

这是使用故事板初始化的示例代码

ViewController *controller = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"<ViewController - string identifier of your view controller>"];
Run Code Online (Sandbox Code Playgroud)

这是使用 NIB/Bundle 进行初始化的示例代码

ViewController *controller = [[ViewController alloc] initWithNibName:@"<ViewController - string NIB name>>" bundle:nil];
Run Code Online (Sandbox Code Playgroud)

根据您的代码和以下评论,仅尝试此代码(从应用程序委托启动中删除其他代码):

// make sure your NIB name is 'ViewController' 

ViewController *controller = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
if (controller != nil) {
    self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController: controller];
    self.window.makeKeyAndVisible;
} else {
   //print - your view controller is nil
}
Run Code Online (Sandbox Code Playgroud)