Cocoa – Creating View Controllers from Code

Starting with an Empty Application, you have a program that contains a single class: AppDelegate and no storyboard. How do you build an application from this? Ignoring main.m and other esoteric code, your application begins at application:didFinishLaunchingWithOptions. When this method is called, your application has an empty window ready for you to populate with interesting objects.

What do you need to make an application? Obviously all of the potential answers are pretty broad. In a wide variety of situations you’ll want a navigation controller. The navigation controller manages views, and transitions between views. It also supplies a navigation bar at the top of the screen. This bar has a title in the center and can have a button on the left and the right.

A navigation controller stores an array of views in a what we call the stack. The first item in the stack is called the root view controller. To switch to a new view you push it onto the stack. To go back to a previous view controller you pop the current view controller off the stack. You can think of push, as adding something, and pop, as removing. The root view is never removed.

Create a navigation controller by creating an instance of theUINavigationController class. Most often you’ll want to initialize your navigation controller with a a root view. Use  initWithRootViewController.

UIViewController *avc = [[UIViewController alloc] init];
UINavigationController *nav = [[MainViewController alloc]  initWithRootViewController:avc];

In this case you are creating two objects. A view controller, and a navigation Controller. When the Navigation controller is created the view controller is set as the root view, which makes this view controller the default view.

In order to see the Navigation Controller and it’s child object on the screen you’ll need to set it as the root view of the window:

[[self window] setRootViewController:mvc];

Leave a Reply

Your email address will not be published. Required fields are marked *