How to set Root View Controller programatically in Objective C?

ios picture ios · Aug 28, 2017 · Viewed 7.6k times · Source

I am a newbie in iOS Development trying to learn how to create and set views programmatically.

i am trying to do swift statement in Obj-C

window?.rootViewController = UINavigationController(rootViewController : ViewController()) 

Project: Single View Application . Trying to link default Created ViewController.h

As per Krunals Answer i updated code but Navigation Controller is not shown in simulator

Cmd+Click on controller does not navigate to ViewController File

#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] ;

Answer

Krunal picture Krunal · Aug 28, 2017

Initialise your view controller ViewController before you add (use as root controller of navigation) into navigation controller stack.

Here is sample code to initialise simple view controller

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

Here is sample code to initialise using storyboard

ViewController *controller = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"<ViewController - string identifier of your view controller>"];

Here is sample code to initialise using NIB/Bundle

ViewController *controller = [[ViewController alloc] initWithNibName:@"<ViewController - string NIB name>>" bundle:nil];

According to your code and following comment try this code only (remove other codes from your app delegate launch):

// 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
}