How to Use a View Controller Programatically

by mattjdrake on May 28, 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.

#import "TipOfTheWeekAppDelegate.h"
//import your view controller interface file below:
#import "ViewController.h"
//this will reference your project name
@implementation TipOfTheWeekAppDelegate
@synthesize window;
ViewController *vc;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
 vc = [[ViewController alloc]
initWithNibName:nil bundle:nil];

[window makeKeyAndVisible];
}
- (void)dealloc {
 [vc release];

[window release];
[super dealloc];
}

@end

Add Your View Controller Object to the App Window

#import "TipOfTheWeekAppDelegate.h"
//import your view controller interface file below:
#import "ViewController.h"
//this will reference your project name
@implementation TipOfTheWeekAppDelegate
@synthesize window;
ViewController *vc;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
vc = [[ViewController alloc]
initWithNibName:nil bundle:nil];
 [window addSubview:vc.view];

[window makeKeyAndVisible];
}
- (void)dealloc {
[vc release];
[window release];
[super dealloc];
}

@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:

#import "ViewController.h"
@implementation ViewController
UILabel *label;
- (void)loadView{
[super loadView];

 CGRect frame = CGRectMake(10, 10, 300, 300);
label = [[UILabel alloc] initWithFrame:frame];
label.textAlignment = UITextAlignmentCenter;
label.font = [UIFont fontWithName:@"Verdana" size:36];
label.text = @"10";
[self.view addSubview:label];

}

- (void)dealloc {
 [label release];
[super dealloc];
}

@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?

kick it on iPhoneKicks.com

Please share this if you like it!
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • email
  • FriendFeed
  • LinkedIn
  • MySpace
  • Ping.fm
  • StumbleUpon
  • Suggest to Techmeme via Twitter
  • Technorati
  • Tumblr
  • Yahoo! Bookmarks

{ 2 trackbacks }

iPhoneKicks.com
June 1, 2009 at 2:34 pm
How to Use a Slider | How to Make iPhone Apps
June 4, 2009 at 9:40 am

{ 6 comments }

1 marlenez@mac.comNo Gravatar May 28, 2009 at 3:24 pm

I use both, don’t really have a preference. When I first started programming on the iPhone I tended to not use IB because making the connections was confusing until you get the hang of it. I actually think that doing it in code is faster.

2 wuf810No Gravatar May 28, 2009 at 6:41 pm

Much prefer Interface Builder and use it the majority of the time. Why have a graphical tool to do the do and then not use it. Obviously there are certain things that can’t be done but I then use IB as the base and then add the required code after.

3 mattjdrakeNo Gravatar May 29, 2009 at 8:39 am

Thanks for the comments! I am going to try yet again to work with IB and see if it has any benefits. One thing I do like is that it helps out layout the components in a visually pleasing way. It just seems that it is pointless for certain controls like date pickers and table views. (to me).

4 coreyfloydNo Gravatar June 1, 2009 at 4:52 pm

First I used IB because it seemed easy. Then I realized that complicated things were hard in IB and I went on to doing (and learning) programatic techniques. This went on for a while and helped me learn some solid principles.
Later I became angry, knowing that IB was a good tool and should be making my life easier. So I went back into IB, and everything made sense. I was able to link nibs together to accomplish complex tasks that I thought needed to be done programatically. I actually use nibs for my UITableView Cells, which works surprisingly fast (For text only so far).
My use of IB is almost hybrid now. You can plan to split up your views amongst nibs in certain ways to get flexibility when you need it.
One iPhone complaint I have is the limited control of TableViews in IB. For something so central to the iPhone, it seems like they should be drag drop and go. The design of most TableView data sources us pretty similar and should allow for great control in IB.

5 dannygNo Gravatar June 1, 2009 at 5:06 pm

I talk about my conversion to IB in one of my blog postings:

http://dannyg.com/iapps/Blog/Entries/2009/4/16_How_I_Grew_to_Love_Interface_Builder.html

6 mattjdrakeNo Gravatar June 2, 2009 at 1:19 pm

@coreyfloyd, @dannyg – thanks for the comments guys. I guess that one of the “problems” I have with IB is that I mostly use table views in my apps. So, not much of a value add for me. But, I am going to give IB another shot starting with my blog posts for next week. I should like it is since I use the similar-ish tool in keynote all the time.

PS: one last vent. – I was just reading through @dannyg’s blog post about learning IB. And it occurs to me that a tool that is meant to simplify things should not require such a lengthly detailed article to explain different ways of essentially coping with the tool. [good post though].

Comments on this entry are closed.

Previous post: 3 Great Articles About iPhone Marketing

Next post: At $.99 a Pop Can You Afford Sparkling Customer Service?