How to Use a View Controller Programatically

Matthew Campbell, May 28th, 2009

iStock_000004484548XSmall.jpgView Controllers are responsible for managing the graphical elements (the View) that appear on the screen of the iPhone. The graphical elements that make up the view can be created in Interface Builder (IB) or in code.

Some people prefer to use Interface Builder while others prefer to use code. As the statisticians in my last job used to say,

“Some like to see the pictures and some like to read the book”.

Using IB is like seeing the pictures – you see all the controls in front of you and you can lay them out visually. Writing code is like reading the book – you know precisely what is going on with the controls because you can see all the code that they are using.

Pros, Cons & a Confession

I should say right up front that I do not like Interface Builder. It never really made sense to me and I found it difficult to work with. That being said, many people do like IB because it comes with tools that help you lay out your controls in a pleasing way. You can experiment easily with your UI without constantly rebuilding your project to see the results of your code changes.

At any rate, today I am going to show you how to load a view controller with a label in code. I am hoping to use this as an example for the next few posts that will demonstrate different user controls. In the future I am thinking about comparing and constrasting doing these tasks in IB and in code.

Adding a View Controller & Label in Code

Add a New UIViewController Subclass

From your XCode project, select “File”, “New File…” and then “UIViewController Subclass”. This adds a new UIViewController subclass to your XCode project.

Instantiate a New Object Using initWithNibName

Go to your app delegate’s implementation file (this is the file prefixed with your project name with the words “AppDelegate.m” attached to the end. Type this code into the applicationDidFinishLaunching method to instantiate your view controller and add it’s view to your app window. Don’t forget to import your view controller’s interface file at the top of the file.

@end

Add Your View Controller Object to the App Window

@end

Add UI Elements to the View in the View Controller Objects’ loadView Method

To do this step go to your view controller’s implementation file and find the loadView method. Simply add the code here that you need to create your user controls that will appear on the screen. For example, I will add a button to my view controller:

@end

So, that is it. It really only takes three steps to create a view controller and then load its view into your app. In the next few posts I am going to build on this example using different user controls.

My Question to YOU:

Do you prefer to use visual tools like Interface Builder or who you rather use code exclusively? Why or why not?