Interface Builder is good tool for building complex user interfaces for the Mac and iPhone platform. It is, however, a non intuitive program when you first start using it - at least it was for me. This tutorial is here to explain how to use Interface Builder to build your first iPhone application. You can also check out our tutorial on building an iPhone application without using Interface Builder if that seems more up your alley.
Today's tutorial will end with a simple "hello world" application being built. The application will take a name in and spit out a simple hello phrase with your name included. This is done using just a text input, label, and single button. You can check out a quick little video our of application below.
The first thing we are going to do is get our project started, which we do in Xcode. This is easily done, go to File > New Project and choose "Application" under iPhone OS. Click "Choose" and give it a name and we're good to go.
Well, now it is time to open up Interface Builder. The first item on the agenda is to create our main view. Go to File > New, select User Interface on the left and choose "View XIB", I named mine SimpleUIView. Once created we can add our text input, label, and button to it. I also update the background color on the view to give it a little bit of personality. Below is a video demonstrating setting up the interface.
The next step is creating the view controller that will handle the bulk of our logic. We are going to go back to Xcode to handle this. We add the file by going to File > New File, select Cocoa Touch Class on the left and then choose "UIViewController subclass" as the template. I also made sure that "With XIB for user interface" wasn't selected. Once chosen I named mine "SimpleUIViewController".
Starting in the header file "SimpleUIViewController.h", we add the properties and instance variables we are going to use for our application. We add a variable and property for the label and text input. In order for Interface Builder to know about these we need to mark them as an IBOutlet, as seen below. We also add a variable and property for storing the name entered. A method for changing the label that will be hooked up to our button is also added. The method needs to be tagged as an IBAction, again for Interface Builder. The final item for the header is adding that our controller implements the UITextFieldDelegate.
@interface SimpleUIViewController : UIViewController <UITextFieldDelegate> {
UITextField *textInput;
UILabel *label;
NSString *name;
}
@property (nonatomic, retain) IBOutlet UITextField *textInput;
@property (nonatomic, retain) IBOutlet UILabel *label;
@property (nonatomic, copy) NSString *name;
- (IBAction)changeGreeting:(id)sender;
@end
The implementation file "SimpleUIViewController.m" starts with a number of commented out methods. We don't need any of them so you can delete them if you would like. To have Objective-C handle creating our getters and setters we use @synthesize. Our properties need to have their memory released, this is done inside the overridden -(void)dealloc method. With these updates our file looks like the following:
@implementation SimpleUIViewController
@synthesize textInput;
@synthesize label;
@synthesize name;
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Release anything that's not essential, such as cached data
}
- (void)dealloc {
[textInput release];
[label release];
[name release];
[super dealloc];
}
@end
Along with the above we also need to implement our action method and a text field delegate method. The first changeGreeting handles updating the label with our hello phrase. It starts by saving the input from the user in our name property. Then it will default the name to "Inigo Montoya" if the name is of length 0 (nothing was entered). After this we create a greeting and update it with the phrase of the day. The label's text is then updated and a tib bit of clean up is required.
The second function is not nearly as complex, it simply checks to see if the passed in text field is equal to our property. If this is the case we return YES which in turn closes the software keyboard.
@implementation SimpleUIViewController
@synthesize textInput;
@synthesize label;
@synthesize name;
- (IBAction)changeGreeting:(id)sender {
self.name = textInput.text;
NSString *nameString = name;
if([nameString length] == 0) {
nameString = @"Inigo Montoya";
}
NSString *greeting = [[NSString alloc]
initWithFormat:@"Hello, my name is %@!", nameString];
label.text = greeting;
[greeting release];
}
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
if(theTextField == textInput) {
[textInput resignFirstResponder];
}
return YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Release anything that's not essential, such as cached data
}
- (void)dealloc {
[textInput release];
[label release];
[name release];
[super dealloc];
}
@end
Having the controller created is only one part of it, we now have to do two more things to have it actually work. The first is to update our application delegate ("SimpleUIAppDelegate.h" and "SimpleUIAppDelegate.m") to create the controller and initialize it.
The header for the delegate needs to have an instance variable and property created for our controller. In order for this to work correctly we need to tell the file about our class using @class SimpleUIViewController. This leaves us with a pretty simple header file.
@class SimpleUIViewController;
@interface SimpleUIAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
SimpleUIViewController *viewController;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) SimpleUIViewController *viewController;
@end
The default implementation of the application delegate already overrides applicationDidFinishLaunching which is where we are going to allocate and initialize our controller. The controller is initialized using the instance method initWithNibName with the first parameter equal to the name our view nib which is equal to the name of our view, in my case "SimpleUIView". Before leaving the file we need to make sure we @synthesize our property and import the SimpleUIViewController header. The last thing we need to do in the implementation file is make sure to import the "SimpleUIViewController.h" file.
#import "SimpleUIViewController.h"
@implementation SimpleUIAppDelegate
@synthesize window;
@synthesize viewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after application launch
SimpleUIViewController *aViewController = [[SimpleUIViewController alloc]
initWithNibName:@"SimpleUIView"
bundle:[NSBundle mainBundle]];
self.viewController = aViewController;
[aViewController release];
[window addSubview:[viewController view]];
// Override point for customization after application launch
[window makeKeyAndVisible];
}
- (void)dealloc {
[window release];
[super dealloc];
}
@end
The final piece is done inside of Interface Builder. We have to open up our view again and this time literally connect our view controller to our view components. Once you have the view ("SimpleUIView.xib") open again in Interface Builder we need to set the File's Owner to be an instance of our controller. This is done in the identity inspector, once completed we have to drag lines from the connection inspector the appropriate items on our view.
Now this can be somewhat confusing so I create the video below to help walk through it. There are a couple tips though. First, Outlets should connect to actual components on the view or the view itself. Second, Actions connect to object events like the "Touch Up Inside" message on our button. Last, but not least, Referencing Outlets set the owner as a delegate of an object in the view. Well, go ahead a take a minute to see for yourself.
If everything has gone correctly you should now be able to run the simulator from Xcode and see something like the demo at the top of the post. That pretty much wraps it up. If you have any questions feel free to leave a comment or go and check out our forums.
08/16/2009 - 19:49
Excellent tutorial and video!
08/17/2009 - 08:41
Thankyou so much,,,,
10/16/2009 - 08:40
Brilliant tutorial...thank you
10/17/2009 - 17:07
Thank you.
I followed this tutorial to add a view into an existing app, and I ran into a problem getting 'SIGABRT' error when the app tried to
pushViewController. The problem was fixed by going back to Interface Builder and choosing the menu: "File/Reload All Class Files".11/29/2009 - 07:13
Simple and nice like 2 previous tutorial, but this one does not work. I think, something with SimpleUIView.
12/28/2009 - 23:44
Yea... there seems to be problem with this tutorial. I am getting this error:
"*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key view.'"
12/30/2009 - 02:34
i cannot find all of it on my windows. is there anything wrong ??
can anybody help me ?
01/25/2010 - 02:33
Hi Guys,
Can you help me out? what may be the needs for being a iphone apps developer (native or web apps)??? can you assist me on the system requirements needed as well the software???
Thanks
02/06/2011 - 00:39
I think you may be better off pursuing an alternate career :)
01/28/2010 - 17:26
This is an old version tutorial...things have changed folks.
01/28/2010 - 17:31
What has changed? I work with XCode everyday and nothing noticeably has changed for me.
09/24/2010 - 05:31
"The first item on the agenda is to create our main view. Go to File > New, select User Interface on the left and choose "View XIB", I named mine SimpleUIView. "
There is no "User Interface" on the left. "View XIB" is nowhere as well. I have lost at this point. Have no idea how to continue :(
09/24/2010 - 08:51
This is a little easier with the latest X-Code. The "New File" dialog can be found by right mouse clicking the project file in the "Groups and Files" window (should be to the left of the text editor). If you have a "Classes" or "Sources" folder beneath the project, right mouse click that instead.
Within the New File dialog, select "Cocoa Touch Class" and then select "UIViewController subclass". By default this will create both the "View XIB" and the UIViewController needed in the tutorial's next step.
02/13/2010 - 17:04
I followed this tutorial, and repeated it several times, by
couldn't get past black screen with status-bar... Please, revise it. And yes - it's NOT the first Interface Builder tutorial, that i followed. It actually first that refuse to produce working app :(
02/15/2010 - 15:52
I just took the entire tutorial, step by step and it worked just fine. I am using Xcode 3.2.1 and iPhone SDK 3.1.3. I did update a couple things in the tutorial to make even easier to follow. Couple items to make sure you did/do are make sure the file owner is set inside of Interface Builder and make sure that you imported the "SimpleUIViewController.h" inside of the app delegate file. I'm sorry you had issues but I promise that it did and still does produce a working application. :)
02/26/2010 - 16:18
This tutorial does not work. I have tried it several times and even just copied and pasted the code in. You must have left out a few details that you haven't noticed because you have a lot of experience and it is second nature to you.
02/26/2010 - 17:23
When I get to the Connections Inspector all that there is:
view
I don't have label and textInput
What doyou think that the problem is?
02/26/2010 - 17:28
Also in the connections inspector I don't have a "Recieved Actions" menu.
03/22/2010 - 09:09
I think the problem is most likely the incorrect item is selected in Interface Builder. I'll look over the tutorial again.
04/27/2011 - 02:14
Also make sure you saved your files :-) That was why it was not showing for me.
03/14/2010 - 17:45
You copied this straight from the iPhone dev site. Except you left out some important details to make this tutorial work. Strong work!!!
03/22/2010 - 09:07
I must have missed this and i really must have missed the videos that posted.
04/05/2010 - 12:50
For those app developers that don't know Objective-C and Cocoa Touch and don't want to outsource development, check out localbeacon (an iphone app builder) at www.bigforge.com. Full integration of Twitter and Facebook, multiple ways to add content into system, off-line access, robust infrastructure including a CDN for all rich content, ability to merge in audio/video and photo galleries, and push notifications. Great for those who want to build just one app or developers interested in white label.
Here's an example of one of our apps - L'Oreal Melbourne Fashion Festival at http://bit.ly/9o2R6S
We would like the chance to earn your business.
05/02/2010 - 11:17
Works just fine - for anyone where it didn't work, did you save the xib file into the xcode project from Interface Builder?
Thanks for all the tutorials btw, easiest to follow that I've found.
05/09/2010 - 06:01
Worked great for me thanks for the guide. The only difference I did find was with the default implementation is slightly different, the first method definition is as below:
// Override point for customization after application launch
[window makeKeyAndVisible];
return YES;
}
But this makes no difference to the workings of the application.
05/21/2010 - 12:44
is any change made to code automatically when we added label to view
07/17/2010 - 13:59
Excellent tutorial. Thanks.
01/09/2011 - 05:00
Please update tutorial.
01/30/2011 - 15:30
Thank you!
I was not setting the File's Owner class -- Now I know how!!
02/10/2011 - 17:13
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) SimpleUIViewController *viewController;
should be
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet SimpleUIViewController *viewController;
02/10/2011 - 18:35
Why does SimpleUIViewController need to be an IBOutlet? IBOutlet's purpose is to alert Interface Builder of possible outlets. Since the view controller is allocated and the property is assigned in applicationDidFinishLaunching, there's no need to mark the property.
02/10/2011 - 19:15
With the latest X-code version if you build a view-controller application from template, it has it this way from the template. I can't say for sure that it was absolutely necessary since I made other changes that could have been blowing things up for me, but that was the one I guessed was causing some issues.
I'm a beginner here - all I know is that it wasn't working for me, made that change - and it started working.
02/17/2011 - 16:52
Doesn't work. This just brings up a blank screen. No errors.
Does this have anything to do with the MainWindow.xib file that XCode autogenerates?
WTF Apple...
03/04/2011 - 08:46
I had the same issue - blank screen on start up and then a crash.
There's a problem I found after a bit of googling - it turns out that if you create a class with an associated nib the nibs filetype set as a 'source.nib'! It should be 'file.nib' for this example to work correctly.
-- right/control click the .nib file and choose Get Info
-- under the generall settings, choose file.nib for filetype
-- you may need to go back into Interface Builder and re-connect the view
I hope that helps some people
03/23/2011 - 08:39
when i go to the connections inspector, i don't get any of the outlets, received actions or the referencing outlets
03/23/2011 - 10:30
where i can download this app ??
05/05/2011 - 21:26
I don't think this works for Xcode 4 because of the default MainWindow.xib file that is created.
05/22/2011 - 15:05
I get the same blank screen but I also see this in my xcode window--
Error from Debugger: mi_cmd_stack_list_frames: Not enough frames in stack
However it does build successfully and opens on my phone but the screen remains blank.
It does not operate at all on either of the sims iPhone or iPad it simply crashes there.
I also checked the and the file type is file.nib so that is not my issue but thanks Julian it was a thought
Any other ideas
05/22/2011 - 18:49
Well I figured mine out. When xcode saves all the files when doing a build and run. For some reason myview file was not saved in the process of closing things down to work on something else I noticed it asked me when I went to close interface builder if I wanted to save the file I did so and my App started working no more blank screen everything came up as expected.
Thanks for the tutorial and I hope my little setback helps others.
07/28/2011 - 23:43
Hi guys, I'm having a problem...
I'm using xcode 3.2.6
and simulator 4.3
When I run the simulation it opens fine, but the button does not work.
Where did I go wrong?
07/30/2011 - 14:21
well written tutorial.perfect for beginners to understand the connections. Thanks!
08/28/2011 - 16:08
Thank you. Now
So much tedious BS in terms of setting up the controller and manually coding outlets.... The tools should handle this sort of thing for you (or at least give the option to). Give me Eclipse of VS.NET any day over xCode... it's utter shit in the way in pains a developer in little ways, in many aspects it's like a IDE from the stone age of computing. For an OS that seems to claim so much stake in the future Apple should be ashamed that THIS tutorial would be required at all.
09/02/2011 - 12:56
When i go Xcode > File > New project i don't get the iPhone OS X App option, only the Mac option. Why? Please, Help?
09/02/2011 - 17:04
Is this for XCode 4? It looks different. Can't find these menu commands anywhere.
09/21/2011 - 22:48
Great tutorial....
keep it up.....
09/22/2011 - 08:10
This helped me a lot. Thank you very much! :)
10/25/2011 - 11:44
Does not seem to work
12/01/2011 - 03:59
Give me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! I’m sure you had fun writing this article.
http://www.2jdesign.co.uk/
01/29/2012 - 08:29
I'm using Interface Builder 3.2.6. It doesn't work for me. I just get a black screen. I too am surprised how much work needs to be done just for "Hello world". Can't believe you need to run 2 separate IDEs for the interface and for the code. I was in Interface Builder double-clicking on the objects thinking it would bring up the code for that object WHOOPS!
02/01/2012 - 13:13
thanks for sharing
Add Comment
[language] [/language]
Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]
See here for supported languages.
Javascript must be enabled to submit anonymous comments - or you can login.