Finally, we get to write some real code! In this tutorial, I will show you how to create an interface using Interface Builder and connect it to your code. We will be creating a UITextField, UILabel, and a Button. Now, don’t be intimidated that this tutorial is so long. I have really went into detail explaining everything as I go. You could easily scan over it and get the gist of it. Here’s how the application will work:
- The user will tap inside a text box which brings up the iPhone’s keyboard
- The user will type their name using the keyboard
- The user will press a button
- The label will update with a greeting containing that user’s name (ex. “Hello Brandon!”)
- If the user fails to enter in text, the label will say something like “Please Enter Your Name”
Prerequisites: This tutorial assumes that you have completed the following tutorials
In this tutorial you will learn:
- Create a new View-Based application
- Create a simple user interface
- Write code to connect to an interface
- Connect the interface to the code
- Update the interface based on user interaction
Like the last tutorial I wrote, we are going to need only one view. So we will just use Apple’s View-Based Application template. So click File -> New Project. Select View-Based Application and name it ViewBased (You can name it whatever you want).
So like last time, Apple has provided us with most of the code needed to get this app up and running. You can click Build and Go to launch the simulator, but all you will see is blankness.
Let’s get started by double clicking on ViewBasedViewController.xib. This is a nib file that opens with Interface Builder. It contains information regarding the layout and controls of our view. Once you do this, Interface Builder should open up.
It will look something like the screenshot below.
A few notes about interface builder…
Library – The right-most window contains all of your controls that you can add to your view. For this tutorial we will be using a TextField, Label, and Button.
The next window to the left of that contains objects that we will connect our interface to. View represents the view of this nib file (basically the interface). File’s Owner is the object that links the interface to the code.
View - This is your user interface for your iPhone application. This window is where you will drop controls from the right-most window.
Attributes – This is where we will set the styling properties of our controls
Add a Text Field
The first thing you want to do is drag a Text Field from the library box on to your view window. You will see some blue lines to guide you. These are in place to help line up controls as well as center them.
Once you have added the Text Field to the View, move it around until it’s in a position that you are happy with. Next, stretch each side of the text box so that it spans accross almost the entire view area. (The blue lines on the right and left will let you know when to stop.)
Now we are going to set some of the attributes of the Text Field. If the Attributes Inspector doesn’t appear, click on the Text Field and then click Tools -> Attributes Inspector.
- In the Placeholder field type in Name. This is the default text that appears in the Text Field before a user types anything.
- For Capitalize select Words – This tells XCode that we want to capitalize each word
- For Return Key – Select Done. This makes the return key on the keyboard say Done rather than return.
- Also, make sure Clear When Edit Begins is checked
Add a Label
Drag a Label from the Library onto your view. Similarly, stretch it the length of your view and place it where you would like. Let’s change the default text of the label. If the Attributes Inspector doesn’t appear, click on the Label and then click Tools -> Attributes Inspector. In the Text field type in “Enter your name above” (or below depending on where you chose to put the label in relation to the Text Field.
Add a Button
Now drag a Button from the library onto your view. Stretch it and position it however you would like. Now we need to add some text to the Button. Click on the button and then click Tools -> Attributes Inspector. In the Title field, type “Display“.
We are now done creating our interface. It should look something like this:
Let’s return to our code… Close Interface Builder and go back to Xcode.
The files that link an interface to some code are called View Controllers. Let’s open up ViewBasedViewController.h. This is the file where we will declare all of our interface variables. Add the following code to you ViewBasedViewController.h.
Interface Builder uses IBOutlets and IBActions to connect to the code. Here is a brief explanation of each line of code.
- IBOutlet UITextField *textName – creates an outlet to connect to the text field we created in interface builder. We use this variable to get information from the text field.
- IBOutlet UILabel *lblHello – An outlet that connects our label on our interface to the code. This variable is used to set the value of the label.
Now that we have declared these variables, we need to make them properties. This allows us to set certain attributes that are associated with the variables. Retain tells the compiler that we will handle the memory management of this object (don’t forget to release it when you are done). Otherwise it will get “cleaned” after being instantiated.
There is one other thing here.
- (IBAction) updateText:(id) sender;
This is the function that will get called when the user presses the button that was created in Interface Builder. We are simply declaring it here in the header file. We will implement this function a little later in the tutorial. Now, we need to connect the interface to the code. Double click on ViewBasedViewController.xib again to open up Interface Builder.
- Connect the View
- Click anywhere on the background of your view (anywhere that is not the Text Field, Label, or Button). Now click Tools -> Connections Inspector. Next to New Referencing Outlet, you will see a circle. Click in that circle and drag the blue line to the File’s Owner object and release it. The word view should pop up. Click on it. You have now connected the view to your proxy object. You should now see:

- Connect the Text Field
- Click on the Text Field in your View window to select it. Then click Tools -> Connections Inspector. You will now see a circle next to New Referencing Outlet. Click in that circle and drag it over to the File’s Owner object. A message will pop up with txtName. Click on txtName and the connection is made. You should now see:
-

- Connect the Label
- Click on the Label in your View window to select it. Then click Tools -> Connections Inspector. You will now see a circle next to New Referencing Outlet. Click in that circle and drag it over to the File’s Owner object. A message will pop up with lblHello. Click on lblHello and the connection is made. You should now see:

- Connect the Button
- Click on the Button in your View window to select it. Then click Tools -> Connections Inspector. You will now see a circle next to Touch Up Inside. This is the trigger that gets called when a user presses the button. Click in that circle and drag it over to the File’s Owner object. A message will pop up with updateText. Click on updateText and the connection is made. You should now see:

Now all of the connections should be set up. Go ahead and close Interface Builder. We are done using it.
Open up the file ViewBasedViewController.m . This is the file where we will implement the updateText function. Add the following code…
This code is pretty straight forward and easy to follow. I will explain it line-by-line:
@synthesize txtName,lblHello;
Most of the time when creating (private) variables, you need to specify what are called “getter” and “setter” methods. Theses functions get the value of a variable and set the value of a variable. What synthesize does is creates these methods for you under the hood. Pretty handy…
Next we will implement our updateText method. I started by creating a temporary string. This is the string that we will insert into the text of the label.
The next line checks to see if the user has entered any text int the Text Field. txtName.text returns an NSString. We are simply calling the length method on a string. If the length is 0, then obviously the user has not entered any text. If this is the case, we set the temporary string to “Please enter your name”: instructing the user to enter in their name.
If the user has entered in some text, a new string is allocated. The initWithFormat method is similar to printf in C. So, I used the string “Hello %@!”. The “%@” in the string means we will be substituting it for a string. To get the value of the Text Field we again use the txtName.text property.
Finally, the value of the Label is set by calling lblHello.text. This calls the text property of label and sets the text to our temporary string variable.
The last line [text release]; releases the temporary text field from memory. This is necessary to write an efficient iPhone application. If you want to know why a lot of iPhone apps crash, it’s because the developers don’t follow through with this step.
That’s it! Click Build and Go. The application should launch in the iPhone Simulator. When you click inside the Text Field it should bring up the iPhone’s keyboard (you can also type with your keyboard). Enter in your name and click “Display”. Here are a few screens of what your app should look like.
User Clicks Display without typing in their name
User types in their name and clicks Display
Well, that concludes this tutorial. I hope that I was able to help you out on your road to iPhone glory. If you get lost at any point you can download the code to this tutorial here ViewBasedSampleCode. As always, if you have any questions or comments, be sure to leave them in the comments section of this page. Happy iCoding!













167 Comments
As usual good effort. One typo error though:
@property(nonatomic, retain) IBOutlet UITextField *lblHello;
should be –>
@property(nonatomic, retain) IBOutlet UILabel *lblHello;
Brandon do you know how to remove those unused projects on the iphone simulator? I try deleting them on my document folders but they still show up on the simulator. Thanks
Adam,
Good catch man. I guess that I was taking screens before I actually compiled. I went back to the code and realized that I had changed it but never updated the screenshot.
As far as removing the old projects, when running the iphone simulator, you can click the iPhone Simiulator menu and click “Reset Content and Settings…”
This will remove all of your installed applications, which really isn’t a problem since you don’t really need them to be saved on the simulator.
Hope that helps.
How do you make it so when you click the “Done” button on the keyboard that it goes away? Currently with the code you have explained the “Done” button does not do anything.
Other than that, great tutorial.
Thanks.
Thanks Brandon, great tutorial as always – just a couple of questions
1) how do you make the text in the UITextField larger, i’ve tried adjusting the font in interface builder but this doesnt change anything.
2) As with Jons question, i’d like to know how to use the “done” button on the keyboard so that it minimises and also does a submit (in place of the button we added in interface builder)
Thanks.
I followed your instructions step by step and there comes some problems for me on the interface “Connect the interface to code stage.” I just get view popping up for all 4 parts when i drag the blue line over to File’s Owner. It doesn’t link it correctly for me. Anyone know why?
At Phil,
I think I have answered your question in experimenting myself. In Interface Builder, similar to dragging the Touch Up Inside for the button to the updateLabel method, for the textfield, drag from Did End On Exit to that same method. That works.
T, did you first connect the view object? I’m at work now, I’ll experiment with it a bit when I get home and try to have a better response for you.
Jon, thanks for the input man. When I get home, I’ll play with that as well and update the tutorial.
Ok, so I figured out how to hide the keyboard when the user clicks the “Display” button. Add the following code to the “updateText” method:
[txtName resignFirstResponder];
Jon was correct on how to hide the keyboard when the user presses “Done”.
T, I went through the tutorial over and over again trying to solve your problem. I wonder if you skipped a step…Do you have the latest version of the iPhone SDK?
Great work brandon,
It is very helpfull to the begineer like me.
At last i got the flow with this …thanks.
O, I think that is it. I have a version from 3 weeks ago. I guess they update the SDK often and I didn’t update mine. I am updating my SDK now. I am sure that was the problem I was having.
Confirmed, my SDK needed to be updated for these features. It works now, thanks again.
Thanks for all the input. After adding the features Jon talked about, One thing I noticed, if I did a Display click while inputing the name, then the name comes out in lower case on the first click. On the second click it will be capitalized. This isn’t a problem, just a little thing I noticed.
Great work!!
I have been trying to figure out IB for a week and finally things are starting to make sense.
Thank you.
This is very helpful. These step-by-step examples are really easy to follow and bridge the gap between Apple’s reference docs and their code samples. I look forward to the next tutorial. May I suggest one showing how to use the UINavigationController?
Many thanks, and keep it up!
-c
Thanks for this tutorial. It helped me to understand how to start simple programing.
Adam: To remove programs from simulator, just hold left mouse in simulator for 2sec and you will know what to do.
Thanks Brandon.
Radek: Hey thanks a lot, that really helps. I wanted to remove the icons without clearing all my contact infos on the simulator.
Thanks a lot. Keep it up!
Thanks! Great stuff!
These examples have helped a lot! I think it would be very helpful to see a tutorial about popping views in and out of a navigation controller.
I’m glad I could help. I actually have been working on a tutorial that details how to transition between views. It should be up later tonight.
great work!!! thank You very much! please go on in this way, it is very usefull for me!
Great tutorial. Clarified quite a few things for me.
I got one more question. I know you have another tutorial using Navigation Controller to switch between view, now I wonder in this Hello World, how can you put a button and on the touch down event display another view? I tried creating new XIB View and ViewController, but couldn’t get it to work.
Also, do we need ViewController for each view, or for each XIB file? Can we have multiple views in a XIB file?
Thanks,
@Zia
The way you would go about this is very similar to this post.
You seem to have a good start…
This should be about it. Let me know if you have any more questions…
@Brandon,
Thanks for your reply. After following the steps, I dont see any errors when I click the button, and I see that the View2Controller::initWithNibName gets called, but it does not change the display.
Is there anyway I can debug self.navigationController?
Also, I started off this project as View based application and not Navigation based one.
Thanks,
did you push your instance of View2Controller onto the navigationcontroller stack?
@Brandon,
yes. as per your other tutorial, i used
[self.navigationController pushViewController:self.view2Controller animated:YES];
where view2Controller is the controller i created for View2.xib
@Zia
Hrm…did you complete this step? This usually is the problem if there is not error but it’s not doing anything.
Yes. I’ve uploaded the project directory for you, in case you have time to look at it.
Thanks for you help.
http://tinyurl.com/58l6ak
Brandon – thanks for this, it is excellent!!
I have one question – I am having the same problem as T was having in that I only see “view” appear when I attempt to connect the different elements of the interface to “File’s Owner”.
How do I update the SDK software, I downloaded it a couple of weeks ago, would I therefore need to update it to overcome this problem?
To update the SDK software, you need to go to developer.apple.com/iphone login and download the SDK. Thanks for reading!
Great Tutorials, would be nice to get them linked in a chapter like flow. This would greatly help newbies to the iPhone Dev world. I have spent several hours looking through the Apple iPhone Dev docs and nothing really comes close to explaining things like you have done here.
Fantastic write up!!!
Thanks mate. Great Tut.
H
Keep up the good work, so far those are the best tutorials I found on the Web
Hi…
Thanks for your tutorial.
But I try to do some stuff like moving the label to the left or right. It works if I just move it for x pixels. But if I try to use Delay(int, unsigned long*)
It won’t refresh the label until the loop is finished.
Do you have any example to move the label 10 times (each 5pixels)? just like a simple animation…
Thanks..
Wow I’m learning more in one afternoon about iPhone programming here than a whole week on Apple’s site.
K-u-d-o-s
First off, great tutorial. This was LOADS of help
I am concerned about the proper way to hide the keyboard once “Done” is clicked. The methods mentioned above seem to work well, but I’m wondering if that’s the correct way to handle the problem? My only issue is that they require the updateText method to be called, which by design shouldn’t really be called until we click the button (plus, with my screen design it’s hidden by the keyboard. I can’t click it without the keyboard gone =\).
From what I can tell, all that has to be done to achieve this result is hook the text field’s “Did End on Exit” method up to any action. If you do that, the keyboard will exit when ‘Done’ is pressed. I created a separate action called “releaseKeyboard:” that does absolutley nothing. No code executes in this action. When I hook my text field’s “Did End on Exit” method to it, the keyboard hid when I clicked ‘Done’.
What solutions have others come up with? Like I said, the ones mentioned by other users above seem to work, however they require the updateText method to be called, which I’m trying to avoid.
Thanks again for all the help folks,
-B
@Brandon #2,
First of all, great name…
Second, I have not seen a better solution to this problem. You could simply make a method called “hideKeyboard” that only hides the keyboard.
Connect the “Did End on Exit” to this method. If you end up finding a better solution, please post it. I’m sure it would be useful to many.
Thanks for posting!
Ok, a quick update about hiding the keyboards. This solution works for any keyboard that has a “Done” or “Return” button. All you have to do is add a method to the delegate that is assigned to your text field on the connections tab of the Inspector menu.
Add the following method to your delegate:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {[textField resignFirstResponder];
return YES;
}
Any text fields assigned to a delegate that have this method implemented will hide their keyboards once completed. You don’t have to hook any events to any actions, just make sure the delegate implements that method. This doesn’t work for the number pad though, since it doesn’t have a “return” or “done” key. I’m assuming the best way to release the number pad is to hide it whenever someone touches outside the pad, but I haven’t figured out how to make that happen, yet.
I’m assuming this method might be a little more architecturally ‘sound’ as it would allow a developer to create separate delegates for text fields to handle input processing and validation instead of running all your fields through a single controller, but I’m by no means an experience software architect. That’s just my assumption.
If anyone has any suggestions on how to hide that darn number pad, I’d greatly appreciate it
Hope this helps,
-B
Great find Brandon! This is really helpful
I have followed along with the other tutorials and all has gone fine. My problem now is when I enter in *txtName and *lblHello they dont change color they just stay black. I think that this is causing problems when trying to link items in interface builder. Any ideas?
@Mike,
When you say it’s staying black, is this in your ViewBasedViewController.h? What is the specific error that you are running into?
You can also download the sample code and compare it to yours…
Some may be experiencing funky problems due to using Interface Builder (IB) with Xcode no longer running (with the correct project) in the background while they build the interface in IB.
They may have accidentally closed Xcode, created certain items in IB that are best created in Xcode (say after deleting them by accident), etc.
Just throwing that out there as Apple recommends that Xcode remains running with the current project open when using Interface Builder for the two to communicate changes:
http://developer.apple.com/iphone/library/documentation/DeveloperTools/
Conceptual/IB_UserGuide/CodeIntegration/chapter_8_section_1.html#//apple_ref/doc/uid/TP40005344-CH18-SW1
Harry “wishes he found this excellent blog weeks ago” Wang
Hi,
It’s really usefull one, I am trying do a application similar like flixters movies.app, can you show us how they are working? like connecting to web site or web database.
thanx
Thanks so much for the tutorial. Apple does have similar to this called “iPhone Application Tutorial” in their documentation.
I’m have trouble with hiding the keyboard when “Done” is tapped. Am I supposed to put the -(BOOL)textFieldShouldReturn method in ‘ViewBasedViewController.m’? I’ve tried it and the Done key doesn’t hide the keyboard. It does however correct misspelled words.
I would appreciate any help on this keyboard problem. Thank you.
Oops. I found out the problem with the keyboard.
In Interface Builder, with the UITextField selected, I saw in the properties inspector that ‘delegate’ was not attached to anything. I just connected the ‘delegate’ to the File’s Owner proxy and the -(BOOL)textFieldShouldReturn method hid the keyboard automatically.
Sorry, I just started learning XCode 3 days ago.
Very nice tutorials. Bravo!
To make the “done” button close the keyboard I
usually put this code in the *.m controller’s file:
-(BOOL)textFieldShouldReturn:(UITextField *)theTextField {
[txtName resignFirstResponder];
}
return YES;
}
But you also shoud delegate the File’s Owner by selecting the textbox in IB ->Field Connections->delegate File’s Owner.
Saluti!
…sorry a “}” too much before “return YES;”
I have the same problem..
“interface “Connect the interface to code stage.” I just get view popping up for all 4 parts when i drag the blue line over to File’s Owner. It doesn’t link it correctly for me.”
I have the newest SDK. Anybody knows how to solve this problem?
Thanks, Tom
Have you downloaded the source code and compared it to your code? This sounds like a type-o (it usually is)…
Thanks for the tutorial. How would I enter “Please enter name” to be put in the “Text Box” as opposed to the “Text Label”. I was trying to mess around with it but guess I’m still to new to this language. Thanks.
5 Trackbacks
[...] iPhone Programming Tutorial – Connecting Code to An Interface Builder View [...]
[...] Connecting Code To An Interface [...]
[...] you are unfamiliar with what is happening here, read the tutorial Connecting Code To An Interface Builder View. We are simply making the connections between our UIComponents to the code. This will allow us to [...]
[...] iPhone Programming Tutorial – Connecting Code to An Interface Builder View This is fantastic hands-on tutorial of what is involved to get Interface Builder to wire up some buttons for you in your app. It’s long, has lot’s of screen shots, and there are excellent comments at the bottom of the article. The comments are great because they really help you understand the mindset needed to program. var addthis_language = 'en';var addthis_options = 'email, favorites, digg, delicious, stumbleupon, google, facebook, reddit, live, more'; Related Posts:10 Reasons to use the Hybrid Framework for WordPressHow to get Google Analytics stats for today only with one simple click14 Top Typeface and Font Combinations ResourcesThe Best Monitor for Graphic DesignHourly rate or by-the-project pros and cons for graphic design fees [...]
[...] After creating the interface, make sure you hook up all of the UI components to their corresponding IBOutlets and hook up the touchUpInside: method of the button the your scheduleAlarm: IBAction. For more info on hooking up IBOutlets, check out this tutorial. [...]