Sunday, June 9, 2013

UINavigationController initWithRootViewController example in Objective C (iOS).


UINavigationController initWithRootViewController

Initializes and returns a newly created navigation controller.

- (id)initWithRootViewController:(UIViewController *)rootViewController

Parameters of [UINavigationController initWithRootViewController]
rootViewController
The view controller that resides at the bottom of the navigation stack. This object cannot be an instance of the UITabBarController class.

Return Value
The initialized navigation controller object or nil if there was a problem initializing the object.

Discussion of [UINavigationController initWithRootViewController]
This is a convenience method for initializing the receiver and pushing a root view controller onto the navigation stack. Every navigation stack must have at least one view controller to act as the root.

UINavigationController initWithRootViewController example.
incidentTableViewController = [[IncidentTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
    UINavigationController *controller = [[UINavigationController alloc] initWithRootViewController:incidentTableViewController];
    incidentTableViewController.title = @"Incidents";
    splitViewController = [[UISplitViewController alloc] init];
    splitViewController.viewControllers = [NSArray arrayWithObjects:controller, nil];
    splitViewController.delegate = (id)incidentTableViewController;
    splitViewController.view.frame = CGRectMake(268, 0, 268, 423);
    [self.view addSubview:splitViewController.view];

Example of [UINavigationController initWithRootViewController].
- (void)viewDidLoad {
    [super viewDidLoad];

    PageOneController *one = [[[PageOneController alloc]init] autorelease];
    one.title = @"blah";
    navController = [[UINavigationController alloc] initWithRootViewController:one];
    [self.view addSubview:navController.view];
}

UINavigationController initWithRootViewController example.
- (void)viewDidLoad {
    [super viewDidLoad];

    UIViewController *one = [[[UIViewController alloc] init] autorelease];

    [one.view setBackgroundColor:[UIColor yellowColor]];
    [one setTitle:@"One"];

    navController = [[UINavigationController alloc] initWithRootViewController:one];
    // here 's the key to the whole thing: we're adding the navController's view to the
    // self.view, NOT the one.view! So one would be the home page of the app (or something)
    [self.view addSubview:navController.view];

    one = [[[UIViewController alloc] init] autorelease];

    [one.view setBackgroundColor:[UIColor blueColor]];
    [one setTitle:@"Two"];

    // subsequent views get pushed, pulled, prodded, etc.
    [navController pushViewController:one animated:YES];
}

End of UINavigationController initWithRootViewController example article.