Subscribe ( RSS )

iPhone Programming Tutorials


 

iPhone Programming Tutorial - Connecting Code to An Interface Builder View

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

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:

  1. The user will tap inside a text box which brings up the iPhone’s keyboard
  2. The user will type their name using the keyboard
  3. The user will press a button
  4. The label will update with a greeting containing that user’s name (ex. “Hello Brandon!”)
  5. 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:

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.

  1. Connect the View
    1. 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:
  2. Connect the Text Field
    1. 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:
  3. Connect the Label
    1. 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:
  4. Connect the Button
    1. 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!

 

123 Responses

Adam Says:

July 31st, 2008 at 2:37 am

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

Brandon Says:

July 31st, 2008 at 6:49 am

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.

Jon Says:

July 31st, 2008 at 1:10 pm

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.

Phil Says:

July 31st, 2008 at 2:16 pm

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.

T Says:

July 31st, 2008 at 2:37 pm

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?

Jon Says:

July 31st, 2008 at 2:52 pm

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.

Brandon Says:

July 31st, 2008 at 2:57 pm

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.

Brandon Says:

July 31st, 2008 at 8:40 pm

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?

narendar Says:

August 1st, 2008 at 6:56 am

Great work brandon,

It is very helpfull to the begineer like me.
At last i got the flow with this …thanks.

T Says:

August 1st, 2008 at 2:29 pm

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.

T Says:

August 1st, 2008 at 3:47 pm

Confirmed, my SDK needed to be updated for these features. It works now, thanks again.

T Says:

August 1st, 2008 at 4:17 pm

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.

Jimmy Says:

August 1st, 2008 at 11:13 pm

Great work!!

I have been trying to figure out IB for a week and finally things are starting to make sense.

Thank you.

cryptyk Says:

August 2nd, 2008 at 4:25 pm

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

Radek Says:

August 2nd, 2008 at 9:15 pm

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.

Adam Says:

August 3rd, 2008 at 2:25 am

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.

N-ton Says:

August 3rd, 2008 at 7:07 am

Thanks a lot. Keep it up!

Bill Says:

August 3rd, 2008 at 10:52 am

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.

Brandon Says:

August 3rd, 2008 at 11:48 am

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.

koschka Says:

August 5th, 2008 at 5:12 am

great work!!! thank You very much! please go on in this way, it is very usefull for me!

Zia Says:

August 5th, 2008 at 5:27 pm

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,

Brandon Says:

August 6th, 2008 at 8:39 am

@Zia

The way you would go about this is very similar to this post.

You seem to have a good start…

  • Create a new view in Interface Builder
  • Add it to your project
  • Create the ViewController class
  • Link to the view to the view controller class as seen here
  • Create an IBAction inside of your ViewBasedViewController.h file to handle the button press
  • Add the view transition code into your IBAction method inside of ViewBasedViewController.m (you can see that code here
  • Connect your button to the IBAction you created (instructions found above in the “Connect the Button” section)

This should be about it. Let me know if you have any more questions…

Zia Says:

August 6th, 2008 at 11:04 am

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

Brandon Says:

August 6th, 2008 at 11:11 am

did you push your instance of View2Controller onto the navigationcontroller stack?

Zia Says:

August 6th, 2008 at 12:25 pm

@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

Brandon Says:

August 6th, 2008 at 12:47 pm

@Zia

Hrm…did you complete this step? This usually is the problem if there is not error but it’s not doing anything.

Zia Says:

August 6th, 2008 at 1:58 pm

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

iPhone Dev · iPhoneの開発、どこからスタート? Says:

August 7th, 2008 at 6:09 pm

[...] iPhone Programming Tutorial - Connecting Code to An Interface Builder View [...]

Will Says:

August 9th, 2008 at 6:06 am

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?

Brandon Says:

August 9th, 2008 at 8:50 am

To update the SDK software, you need to go to developer.apple.com/iphone login and download the SDK. Thanks for reading!

iPhone Programming Tutorial - Populating UITableView With An NSArray | iCodeBlog Says:

August 12th, 2008 at 12:20 pm

[...] Connecting Code To An Interface [...]

Chris McIntosh Says:

August 15th, 2008 at 8:30 am

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.

asi Says:

August 17th, 2008 at 10:49 pm

Fantastic write up!!!

Hadrian Says:

August 17th, 2008 at 11:42 pm

Thanks mate. Great Tut.

H

Gilles Says:

August 18th, 2008 at 9:45 am

Keep up the good work, so far those are the best tutorials I found on the Web

Vanderlee Says:

August 20th, 2008 at 9:29 am

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..

Sam Wilson Says:

August 26th, 2008 at 9:23 am

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

Brandon #2 Says:

August 27th, 2008 at 4:50 pm

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

August 27th, 2008 at 5:08 pm

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

Brandon #2 Says:

August 29th, 2008 at 4:50 pm

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

Brandon Says:

August 30th, 2008 at 7:51 am

Great find Brandon! This is really helpful

Mike Says:

September 3rd, 2008 at 12:07 pm

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?

Brandon Says:

September 3rd, 2008 at 1:19 pm

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

Harry Wang Says:

September 3rd, 2008 at 8:40 pm

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

billgajen Says:

September 5th, 2008 at 1:49 am

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

Jon K Says:

September 6th, 2008 at 1:22 pm

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.

Jon K Says:

September 6th, 2008 at 1:30 pm

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.

timo Says:

September 13th, 2008 at 3:32 pm

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!

timo Says:

September 13th, 2008 at 3:34 pm

…sorry a “}” too much before “return YES;”

Tom Says:

September 25th, 2008 at 9:44 am

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

Brandon Says:

September 25th, 2008 at 11:38 am

Have you downloaded the source code and compared it to your code? This sounds like a type-o (it usually is)…

jagz Says:

October 1st, 2008 at 9:34 am

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.

jagz Says:

October 1st, 2008 at 10:57 am

After further evaluation I was able to figure this out on my own. For any other newbie out there doing this tutorial that wants to know I did the following:

I changed: text = @”Please enter your name”;
to: txtName.text =@”Please enter your name”;

iPhone Programming Tutorial - Saving/Retrieving Data Using NSUserDefaults | iCodeBlog Says:

October 3rd, 2008 at 11:01 am

[...] 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 [...]

Dan Says:

October 4th, 2008 at 6:15 pm

Hi Brandon,

I keep getting the error:
warning: “NSString” may not respond to “-lenght”

in the ViewBasedViewController.m file

the debugger error is:
2008-10-04 18:10:57.691 ViewBased[1786:20b] *** -[NSCFString lenght]: unrecognized selector sent to instance 0xa01681a0
2008-10-04 18:10:57.693 ViewBased[1786:20b] *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘*** -[NSCFString lenght]: unrecognized selector sent to instance 0xa01681a0′

Any Idea what I might have done wrong?

Brandon Says:

October 4th, 2008 at 7:04 pm

@Dan,

Yea, it’s just a type-o (it always is). You mispelt the word “length”. Looking at your error, it says “lenght”.
Make sure you change it to the correct spelling.

Hope that helps…

Thanks for reading

gonso75 Says:

October 5th, 2008 at 5:07 am

Great tutorial again!

Ade C Says:

October 17th, 2008 at 6:03 am

Hi, I must be missing something… Other three tut’s worked fine. This one doesnt seem to want to play.

Put the controls on the form, put the code in. when I try step one it already looks like you screenshot for the view connections. I try and drag the line up to ‘File’s Owner’ anyway but nothing happens. I go to step 2 and select the textbox. All I see under Outlets in the connections dialog is delegate. There is no ‘File’s Owner’

Downloaded the latest SDK and your source code. Your source code works gr8. What Am I doing wrong/missing. I want to follow along with your uts but I find I have stumbled at the first hurdle :(

Please Help

Ade C Says:

October 17th, 2008 at 9:23 am

I solved the problem myself by going on to the next tut. I was not linking (dragging the blue line) to the yellow 3d box. I just saw the text ‘File’s Owner’ above the first circle and tried dragging it there DUH! In your next tut you actually show the object window with the ‘File’s Owner’ object int it. Thats when the penny dropped.

Hurrah! It all works now like a charm :)

Brandon Says:

October 17th, 2008 at 5:01 pm

Great, I’m glad to see it worked. This seems to be a very common problem for people following my text tutorials. This step is easy to overlook and doesn’t produce an great error message.

Hopefully, the seeing me complete this action in the video tutorials, will help people to not forget this step.

Thanks for reading…

Puneet Says:

October 23rd, 2008 at 4:00 am

Thanks a lot for your tutorials….:-)

Bernhard Says:

October 26th, 2008 at 1:57 pm

Hello,

Thanks for those tutorials, I’m getting more and more excited writing my own apps.

Thanks,
Bernhard

Cybele Says:

October 28th, 2008 at 9:17 am

Thanks for writing this.

dinamo Says:

October 29th, 2008 at 12:53 pm

Hello,
I have the same problem as T.
When i try to connect objects only “view” pops up. The thing is I’ve downloaded SDK today(Oct 29). So redownloading is not going to fix it lol. Another question is where do you name the objects, like naming label “lblHello”?

Anyway thx for great tutorials!

Brandon Says:

October 29th, 2008 at 1:05 pm

@dinamo,

If only view pops up, that means you did not create the IBOutlets in the ViewBasedViewController.h. This is where I declare/name the objects as well.

You must have missed this step…It should solve your problem.

Thanks for reading

dinamo Says:

October 29th, 2008 at 1:16 pm

thx for quick response, i messed up in that file.

Steve Says:

November 3rd, 2008 at 1:08 pm

When I start writing code, some of the text remains black and the text that is in the tutorial becomes green. I have tried to follow the steps carefully but every time I get the same results. What am I doing wrong.

Bo Says:

November 5th, 2008 at 3:37 pm

heres where I failed, if you have FooController.h/.m, and Foo.h/.m you need to take these steps:
in the FooController.h file add this to the @implementation

so it may look something like this: ‘UIViewController

{’

then in the FooController.m add this:

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
[theTextField resignFirstResponder];
return YES;
}

build, and then get rogaine for the hair you lost!
cheers.bo

Bo Says:

November 5th, 2008 at 3:39 pm

[edit] sorry it trashed the post [edit]

heres where I failed, if you have FooController.h/.m, and Foo.h/.m you need to take these steps:
in the FooController.h file add this to the @implementation

‘<UITextFieldDelegate>’

so it may look something like this: ‘UIViewController

<UITextFieldDelegate> {’

then in the FooController.m add this:

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
[theTextField resignFirstResponder];
return YES;
}

Evelin Says:

November 16th, 2008 at 6:43 am

Hi!

Thanks a lot for your tutorials.
I have just completed this tutorial but I get this error when it started to run:

‘-[UIViewController loadView] loaded the “ViewBasedViewController” nib but no view was set.’

Can you help me ?

Thanks

youssef Says:

November 20th, 2008 at 1:12 am

hi,
i have a problem with a number pad keyboard. i can’t hide it with delegate and textFieldShouldReturn funktion because he has no done button.
i d’ont want to ad a button to hide the keyboard because i have more as a Textfield
how can i validate my TextField so that the user can only input numer?

ahi Says:

November 23rd, 2008 at 10:47 pm

Brandon,

Very nice tutorial! I cannot thank you enough. I’ve been a developer for 9 years and I have never found/appreciated a tutorial this much before - believe me. That should speak volumes (and not because I think I’m even a halfway decent developer)

I mean…I’ve learnt from tutorials before and I will continue to do so. But this one is THE beginning for me to learn more on this platform! I scoured a lot of documentation, but found this one to be the most succint and useful!

Thanks a million!

Steve Says:

December 2nd, 2008 at 1:46 pm

Brandon - Let me also add my appreciation and admiration for the job you’re doing on these tutorials.

I’m sure this will go down as the dumbest question ever, but…

In the implementation for the ‘updateText’ method you specify ‘(id)sender’ as the argument (or is it parameter - I never know).

- My interpretation of what is happening is that the sender for this method will be txtName since we’ve made this the outlet for the UITextField object in our interface. However, this method could (theoretically) be called from any number of other objects (like lblHello).

So my question is - why isn’t ’sender’ used in the method implementation for updateText? It seems that the test to see if the length of the string sent to the message is 0, the conditional should be:

if ([sender.text length] == 0) {

rather than
if ([txtName.text length] == 0) {

Sorry to expose my utter lack of the obvious in how this stuff works. I’d just say that if you were to update this tutorial, in the line-by-line explanation of what this method does, you might want to mention the role of ’sender’.

Thanks again for all your work on this. It’s really helpful.

Angus Says:

December 3rd, 2008 at 6:04 am

Hello,

Just though I’d It’s a great series of tutorials you have here.
I do have one problem though. I’ve followed this tutorial step by step and still have two errors.

1. nsstring undeclared (first used in this function)
2. text undeclared (first used in this function)

These are both after the following part of the code

nsstring *text;

Thanks for any help, Angus

Kugutsumen Says:

December 17th, 2008 at 6:22 am

Really nice tutorials better than the O’Reilly books.

I know this is a tutorial but why not use
COND ? TRUE : FALSE

- (IBAction)updateText:(id)sender {
lblHello.text = [txtName.text length]
? [[NSString alloc] initWithFormat:@”Hello %@!”, txtName.text]
: @”Please enter your name”;
}

Ghulam Mustafa Says:

December 17th, 2008 at 8:33 am

Very nice. Thanks for sharing your knowledge.

John Says:

December 29th, 2008 at 6:04 pm

Hi

I downloaded your source code and it works fine. I compared the code with mine and there is no difference except that when I run my code I get an error message saying

“error: ‘didReceiveMemoryWarning’ undeclared (First use in this function)
error: syntax error before “{” token”

below is the code that I believe was created by the XCode program. What do you think is the problem? Thank you!.

John

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn’t have a superview
// Release anything that’s not essential, such as cached data
}

Brandon Says:

December 30th, 2008 at 8:59 am

@John,

The error might not necessarily be in this method. It generally means you have a mismatched parenthesis somewhere. These types of bugs can be quite a pain to track down. I would look in the code above this method. Hope that helps.

Jennie Says:

January 1st, 2009 at 12:45 pm

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.

Aren’t you using TEXT before you alloc it?
And then you RELEASE it… even if the ALLOC didn’t
happen.

Wouldn’t both of those cause crashes?

Julian Says:

January 4th, 2009 at 3:48 pm

Hi Guys
I can’t get passed Step 2 Connect the text Field.
When I open “Connections Inspector” the variable “txtName” does not appear under “Referencing Outlets”.
I also notice that in ViewBasedController.h, variables “txtName” and “lblHello” are black not green in the code editor?
My Xcode version is 3.1.2 and iPhone SDK is 2.2
Regards
Julian

Ted Says:

January 4th, 2009 at 9:27 pm

Julian, I had the same problem re txtName not appearing. It seems related to no automatic save. To resolve it, I had to go to the Interface Builder menu bar, and press File, Save. I’ve had this problem with other tutorials re I.B. as well.
Ted

Sandeep Says:

January 5th, 2009 at 1:24 am

Thanks, for such nice tutorial…..

Mike Says:

January 5th, 2009 at 3:57 pm

Great tutorial. One observation: The iPhone keyboard does not go away after pressing done. To fix this you can add the following method to the ViewBasedViewController.m file.

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}

Here is what the Apple Documentation had to say on it:

It is your application’s responsibility to dismiss the keyboard at the time of your choosing. You might dismiss the keyboard in response to a specific user action, such as the user tapping a particular button in your user interface. You might also configure your text field delegate to dismiss the keyboard when the user presses the “return” key on the keyboard itself. To dismiss the keyboard, send the resignFirstResponder message to the text field that is currently the first responder. Doing so causes the text field object to end the current editing session (with the delegate object’s consent) and hide the keyboard.

Jeremy White Says:

January 7th, 2009 at 2:11 pm

What I don’t get with the -(BOOL)textFieldShouldReturn:(UITextField *)textfield method is that it can return YES or NO and it doesn’t seem to make a difference, the keyboard still goes away. Why does it return a boolean? Why not return void???

ladoo Says:

January 8th, 2009 at 7:37 pm

@Brandon

This is a great tutorial.

Any thoughts on OpenGL ES tutorials?

Thanks and keep up the great work.

C McCormick Says:

January 11th, 2009 at 10:29 pm

A very helpful tutorial, thanks.

I ran into an error that I had to fix, though I don’t know if it is in the tutorial or a glitch in the SDK. Maybe this will be helpful to someone:
When setting up the ReferencingOutlet for the TextField, I also had to connect the outlet, which was not mentioned in the tutorial. The textfield connections screenshot shows two connections and I only got one when I followed the instructions

James Says:

January 13th, 2009 at 9:33 pm

Great work on this resource- best i’ve seen for the iphone. I seem to be having the same problem that several have had following the tutorial…when making connections the first step “view” will connect to the file owner with view as the sole option. When you try to connect the text box or the label you only get ‘view’ as the sole choice in the gray box. I have read through the entire thread and followed all of the suggestions such as updating the SDK, saving the interface builder work, keeping xcode open and the like and I am still not getting the selections ‘txtName’ or ‘lblHello’ as variables when I try to make the connections. Do you have any suggestions?

Michel Says:

January 14th, 2009 at 1:44 pm

I have the same problem as Julian

His description:

I can’t get passed Step 2 Connect the text Field.
When I open “Connections Inspector” the variable “txtName” does not appear under “Referencing Outlets”.
I also notice that in ViewBasedController.h, variables “txtName” and “lblHello” are black not green in the code editor?

My Xcode version is 3.1.2 and iPhone SDK is 2.2

James Says:

January 14th, 2009 at 2:18 pm

We obviously are having the same problem - Michel, Julian & James (myself)and I would suspect others. FYI - I reinstalled the whole iphone SDK on a clean machine with the latest updates. I tried this tutorial & the ball tutorial with no success on either. I think we have a configuration issue or something preventing xcode & Interface builder from interacting properly. I have heard some discussion about closing xcode, saving interface builder, and some other possible solutions. If either of you solve this please let me know - I will continue and do the same. Brandon- are you aware of any possible configuration issues that may be causing this problem?
Thanks for any help you may be able to provide.

- James
(a Paypal supporter)

James Says:

January 14th, 2009 at 11:02 pm

After working some more with the tutorials this evening, I believe this issue is a bug with the SDK. I was working on the machine with the fresh iphone SDK install with the connection viewer problem. I ran it several times with the same problem of not seeing the ‘ball’ selection in the pop-up menu when you drag to the file owner in interface builder ( This is from the Animation tutorial in which I have been experiencing the same problem as in this tutorial, only this tutorial we are looking for txtName and lblHello) Just for grins I launched the application to run on the simulator from xcode ‘build and Go’ The application launched, and ran. I exited the simulator and returned to interface builder. Using the Connection Viewer and repeating the same steps, along with ‘view’ in the pop up box was ‘ball’ which is what is expected and is shown in the tutorial. No difference other than launching the application once. I tried this on the other machine and sad to report it did not cure that instance. At this point I do not know exactly what the problem or work around is; it works on one machine but not the other. Does this work for anyone else who is experiencing this problem??

Nils Myklebust Says:

January 19th, 2009 at 4:23 pm

I had the same view problems right now.

Above on July 31st, 2008 at 2:37 am
Adam Says:

As usual good effort. One typo error though:
@property(nonatomic, retain) IBOutlet UITextField *lblHello;
should be –>
@property(nonatomic, retain) IBOutlet UILabel *lblHello;

I got the same type because i did a copy/past of the first line to create the last and forgot to change TextField to Label.
That gives the exact problem with view in Interface Builder - or at least my problems disappeared when I fixed this.
May be all of those having this Interface Builder problem has done the same error.

Keep up your super work. I´ll keep going through all your other tutorial´s. Your´s are the way they should be.
I´ll seriously think about a donation!

Nils Myklebust Says:

January 19th, 2009 at 4:29 pm

Now I have also changed the code in ViwBasedViewController in the updateText…. method like this:

if([txtName.text length] == 0) {
lblHello.text = @”Please enter your name”;
}
else
{
lblHello.text = [[NSString alloc] initWithFormat:@”Hello %@!”,txtName.text];
}
[txtName resignFirstResponder];

As you can see I have created no text object and therefore also don´t need the archaic release stuff.
I have simply update lblHello.text directly.
Will this get me a memory leak somehow?
I not, why not always do it this way when the text object isn´t otherwise required?
Will it possibly make a later internationalization harder?

Regards

Arindam Dey Says:

January 20th, 2009 at 11:27 pm

Very very helpful for the beginners in iPhone like me. The screen shots and they descriptions have helped me too much. Many many thanks………

Matt Says:

January 28th, 2009 at 6:27 pm

I had the same problem as James, (getting txtName to show up when dragging it over). I tried closing the viewer, selecting ‘build and go’, opening up the interface builder again and dragging the circle back over again. Voila, txtName popped up instead of view and it worked. Not sure exactly what made the difference but hopefully it helps others who are frustrated.

Carl Says:

February 1st, 2009 at 4:36 pm

Same problem as several other people (not seeing txtName). Quitting and restarting Xcode seemed to solve the problem.

Anuj Tyagi Says:

February 11th, 2009 at 4:01 pm

Great Work…. I learned a lot form just the first three tutorials… Thank you very much..

:o).

Mark H. Delfs Says:

February 15th, 2009 at 9:22 am

*GREAT* tutorial series—PLEASE keep them up! I got so much more out of this series than any book, Apple website, video, etc. What really works is how you EXPLAIN each step and what each line of code DOES. This is IMPERATIVE to understanding this for a beginner such as myself!

DP Says:

February 18th, 2009 at 12:39 am

You are Amazing

Amit6021 Says:

February 18th, 2009 at 6:23 am

Thanks Brandon ,

Really your tutorial help a lot to understand the things
easily .
Great Guidance …

Ryan Quantt Says:

February 22nd, 2009 at 6:30 pm

Hi Brandon,

I am new to the iphone SDK but I have the same problem T has in which only the view element has a File’s Owner node above the new referencing outlet. when I try dragging the outlet node to the owner one nothing happens. I have 2.2 version of the SDK downloaded on November 9, 2008 so that shouldn’t be the problem. Any ideas? Thanks.

Ryan Quantt Says:

February 23rd, 2009 at 1:06 am

Nevermind I figured it out. I just needed to drag the “new referencing outlet” node of the connections inspector window to the File’s Owner icon of .xib window.

Mike Says:

March 1st, 2009 at 6:50 pm

@Ryan and probably T.

I ran into this very problem and I’m pretty sure of the solution. You must make sure you save your changes after editing the header file! If you do not, interface builder is not aware of these new variables and will only allow you to connect to “view”.

I don’t remember this tutorial telling you to save at that point, but it may help avoid some confusion!

Thanks for the tutorials.

Ryan Quantt Says:

March 2nd, 2009 at 7:27 pm

Hi Brandon (or anyone willing to help),
Using this tutorial I created a UIButton that calls an updateTally: function that simply adds an integer to a total every time it is pressed and displays that total in a UILabel. The program crashes every time and I made all the connections correctly with interface builder.
Here is my implemented updateTally function:
@synthesize tally;

-(IBAction) updateTally:(id) sender {
NSString *text;
int total=0;
total=total+1;
text=[[NSString alloc] initWithFormat:@”Tally %@ “, total];
tally.text=text;
[text release];
}

Thanks for your help.

Joe Says:

March 14th, 2009 at 4:05 am

Hey Ryan,

I think it has to do with the fact that using ‘%@’ means you’re going to pass in a string when total is an integer.

Val Says:

March 15th, 2009 at 7:20 am

Hello brandon!
I have a problem.
After launching my app, i press a button.
Label changes to a “Enter your name”
its OK.

but if i type smth in the text field (like Val) and press the button, my application crashes down.

debugger says,that problem is in the
txt = [[NSString alloc] initWithFormat:@”Hello, %@!”,field1.text];
string

As you can see, the variable “txt” can capture the text(because if i dont type anything in Text Field and then press the button, “label1.text=txt;” string is working.

thanks

Val Says:

March 15th, 2009 at 7:28 am

omg,all is ok,sry

Will Says:

March 20th, 2009 at 11:16 pm

There’s another way of removing apps from the simulator without having to reset it.

Just click and hold an app until they all wiggle, then click the “x” to remove it… just like the real iPhone.

Chris Says:

March 24th, 2009 at 10:28 pm

I’ve been learning Objective-C with “Learn Objective-C on the Mac” from Apress.

One of the things I noticed was that you alloc the text string on success and then have to release it (because you did an alloc)

if you change it to : ‘text = [NSString stringWithFormat:@"You're Good %@", txtName.text];’
Then you no longer need to release text because it will have an autorelease.

Or maybe I’ve missed something and there is a very good reason why you’re doing the alloc and release.

Ryan Says:

March 25th, 2009 at 2:02 pm

Hi the first part of my app is very simple and similar to this tutorial. All I am doing is right now is having a UIbutton add one to an int variable every time it is pressed and display the new number in a UILabel.

I have made the proper connections with Interface Builder and there are no errors when compiled, but the app freezed and the “TERMINATING DUE TO UNCAUGHT EXCEPTION” displays. I believe it has to do with converting my int to a string so I can display it. Thanks for any help.

Here is my implementation:

@synthesize tallyLBL;
int tally=0;

-(IBAction) udateTally:(id) sender
{
tally++;
NSString *text;
text=[[NSString alloc] initWithFormat:@”Tally: %d”,tally];

tallyLBL.text=text;
[text release];
}

Rups Says:

April 9th, 2009 at 2:11 am

Hello Brandon,
I am new in iPhone app Developement.
This is my first application.
I am making application having several views.
I have made an view based application something like hello world .

after compiling I am not able to see view on simulator though there is no error in compiling.
shold I make a windows based application.
plz guide me on this.

Rups Says:

April 9th, 2009 at 2:11 am

Hello Brandon,
I am new in iPhone app Developement.
This is my first application.
I am making application having several views.
I have made an view based application something like hello world .

after compiling I am not able to see view on simulator though there is no error in compiling.
should I make a windows based application.
plz guide me on this.

Neil Says:

April 15th, 2009 at 5:57 pm

Hi
great tutorial - love the site - learning loads
a question - i am also reading the book beginning iphone development by Dave Mark et al. which is good too and im learning loads by comparing your different styles however there is something i dont understand they seem to say that in the code above you should add
to the viewcontroller method under the

- (void) dealloc {

section
the variables you declare in the @synthesise command
so in your code above it might read

- (void) dealloc { // this line is there already
[txtname release];
[lblHello release];
[super dealloc]; // this line should already be there
}

@end //there already

they say this avoids extra memory leaks - whats your view? i dont want to do it if not needed
thanks
Neil

MakingMeMark Says:

April 22nd, 2009 at 2:54 am

Many many thanks mate, superb tutorial.
Keep up the good work!

Chris Says:

May 7th, 2009 at 4:12 pm

Great work … simple to the point.

Alex York Says:

May 18th, 2009 at 1:33 pm

I had the same problem as several others (T, Michel, Julian & James) where “txtName” does not appear when dragging the referencing outlet to File’s Owner.

I can confirm what Mike said: it is only “view” that appears because I have not saved everything in XCode before moving to Interface builder!

This was really frustrating me but saving (in fact shutting down XCode and letting it save everything that is open) definately solved the problem.

Alex.

Kelley Says:

June 4th, 2009 at 4:21 pm

I am unable to connect the text and label field to File Owner’s Box. I can connect the view just fine. Could it be some typo in my code? I have called my project HiYaWorld. Should I be click on HiyaWordlViewController.h, because I don’t see ViewBasedViewController. Obviously, I am not familiar with objective-c and am a newbie to this application. Thank you.

LockeCole Says:

June 8th, 2009 at 2:01 pm

@Brandon#2

Just to finish implementing your code, make sure to add the updateText method to the “Editing Did End” event of the Text Field, so that when the Done key is pressed, the label is updated. I don’t know if you explained that clearly.

BRUCE Says:

June 15th, 2009 at 4:04 am

updatetext is giving error : txtname and lblhello are
undeclared in this function

Taro Says:

June 19th, 2009 at 3:13 am

Great tutorials, thanks! :)

Alex Says:

June 21st, 2009 at 2:34 pm

The code builds and compiles but it makes the simulator crash to the home screen when I run it.

My code looks the same as yours…

#import “MyFirstButtonViewController.h”

@implementation MyFirstButtonViewController

@synthesize txtName, lblHello;

- (IBAction) updateText:(id) sender {
NSString *text;
if([txtName.text length] == 0)
{
text = @”Please enter your name”;
}
else
{
text = [[NSString alloc] initWithFormat:@”Hello %@.”,txtName.text];
}
lblHello.text = text;
[text release];
}
#import

@interface MyFirstButtonViewController : UIViewController {
IBOutlet UITextField *txtName;
IBOutlet UILabel *lblHello;
}

@property(nonatomic,retain) IBOutlet UITextField *txtName;
@property(nonatomic,retain) IBOutlet UILabel *lblHello;

- (IBAction) updateText:(id) sender;

@end

Those are my View .m and .h files… what am I doing wrong?

Slim Says:

June 26th, 2009 at 4:27 pm

NSLog(@”I’m so thankful to %@”, txtName.text);

// :-)

Rouge Panes Says:

June 27th, 2009 at 11:35 am

Hi Brandon,

Big thanks! Easy to follow tutorial. Thank you for taking time to create this.

Rouge

Argonomic Says:

June 27th, 2009 at 3:14 pm

It would help for this tutorial if you would provide a screenshot of the interface box that contains the actual “File owner” object. I found that part confusing because I didn’t realize at first that I was meant to drag from the contents of one window to a completely different window.

Thanks!

Leave a Reply