iPhone Programming Tutorial – Connecting Code to An Interface Builder View

July 30th, 2008 Posted by: brandontreb - posted under:Tutorials

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!

  • Adam

    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

  • http://icodeblog.com Brandon

    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

    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

    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

    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

    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.

  • http://icodeblog.com Brandon

    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.

  • http://icodeblog.com Brandon

    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

    Great work brandon,

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

  • T

    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

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

  • T

    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

    Great work!!

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

    Thank you.

  • cryptyk

    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

    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

    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

    Thanks a lot. Keep it up!

  • Bill

    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.

  • http://icodeblog.com Brandon

    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.

  • http://www.ramsy-art.ch koschka

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

  • Zia

    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,

  • http://icodeblog.com Brandon

    @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

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

  • http://icodeblog.com Brandon

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

  • Zia

    @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

  • http://icodeblog.com Brandon

    @Zia

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

  • Zia

    Yes. I’ve uploaded the project directory for you, in case you have time to look at it.

    Thanks for you help.

  • http://www.iphonedev.jp/2008/08/08/iphone%e3%81%ae%e9%96%8b%e7%99%ba%e3%80%81%e3%81%a9%e3%81%93%e3%81%8b%e3%82%89%e3%82%b9%e3%82%bf%e3%83%bc%e3%83%88%ef%bc%9f/ iPhone Dev · iPhoneの開発、どこからスタート?

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

  • http://none Will

    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?

  • http://icodeblog.com Brandon

    To update the SDK software, you need to go to login and download the SDK. Thanks for reading!

  • http://icodeblog.com/2008/08/08/iphone-programming-tutorial-populating-uitableview-with-an-nsarray/ iPhone Programming Tutorial – Populating UITableView With An NSArray | iCodeBlog

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

  • http://NA Chris McIntosh

    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

    Fantastic write up!!!

  • Hadrian

    Thanks mate. Great Tut.

    H

  • Gilles

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

  • http://vanderlee.web.id/mac.php Vanderlee

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

  • http://www.storypixel.com Sam Wilson

    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

    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

  • http://icodeblog.com Brandon

    @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

    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

  • http://icodeblog.com Brandon

    Great find Brandon! This is really helpful

  • http://troublewithWritecodetoconnecttoaninterfacestep Mike

    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?

  • http://icodeblog.com Brandon

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

  • http://www.rawhoo.com Harry Wang

    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:


    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

    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

    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

    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

    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

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

  • Tom

    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

  • http://icodeblog.com Brandon

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

  • jagz

    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

    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”;

  • http://icodeblog.com/2008/10/03/iphone-programming-tutorial-savingretrieving-data-using-nsuserdefaults/ iPhone Programming Tutorial – Saving/Retrieving Data Using NSUserDefaults | iCodeBlog

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

  • http://www.nagel-photo.com Dan

    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?

  • http://icodeblog.com Brandon

    @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

    Great tutorial again!

  • Ade C

    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

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

  • http://icodeblog.com Brandon

    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

    Thanks a lot for your tutorials….:-)

  • Bernhard

    Hello,

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

    Thanks,
    Bernhard

  • http://thorsteninsurance.blogspot.com Cybele

    Thanks for writing this.

  • dinamo

    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!

  • http://icodeblog.com Brandon

    @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

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

  • Steve

    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.

  • http://www.wyzfam.com Bo

    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

  • http://www.wyzfam.com Bo

    [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

    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

    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

    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

    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

    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

    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

    Very nice. Thanks for sharing your knowledge.

  • John

    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
    }

  • http://www.freshapps.com Brandon

    @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

    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

    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

    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

    Thanks, for such nice tutorial…..

  • Mike

    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.

  • http://www.designsapling.com Jeremy White

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

  • http://tbd ladoo

    @Brandon

    This is a great tutorial.

    Any thoughts on OpenGL ES tutorials?

    Thanks and keep up the great work.

  • C McCormick

    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

  • http://www.mbbuilder.com James

    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

    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

  • http://www.mbbuilder.com James

    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

    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

    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

    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

  • http://winmobnnetcf.blogspot.com/ Arindam Dey

    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

    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

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

  • Anuj Tyagi

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

  • http://www.webappgalaxy.com Mark H. Delfs

    *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

    You are Amazing

  • Amit6021

    Thanks Brandon ,

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

  • Ryan Quantt

    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

    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

    @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

    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

    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

    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

    omg,all is ok,sry

  • http://www.altumdesign.com Will

    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

    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

    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

    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

    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

    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

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

  • Chris

    Great work … simple to the point.

  • http://www.alexyork.net/ Alex York

    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.

  • http://web.me.com/kelleyhundley/Mrs._Hundley Kelley

    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.

  • http://www.rtrsolutions.com LockeCole

    @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

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

  • Taro

    Great tutorials, thanks! :)

  • Alex

    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

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

    // :-)

  • Rouge Panes

    Hi Brandon,

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

    Rouge

  • Argonomic

    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!

  • SteveH

    To those of you who kept getting “view” instead of the actual text, it is because you did not do a save in Xcode before you went to IB. Those who shut down Xcode and restarted it found it worked, but that is because it saved the files first, not because it shut down.

  • SteveH

    Brandon,
    I get four errors in the .m file:

    After:
    lblHello.txt = text;
    it says:
    error: request for member ‘txt’ in something not a structure or union

    After:
    - (void)didReceiveMemoryWarning {
    it says:
    error: ‘didReceivememoryWarning’ undeclared (first use in this function)
    error: expected ‘;’ before ‘{‘ token

    After:
    @end
    it says:
    error: expected declaration or statement at end of input

    I can’t figure out any of these.

    Thanks for a great tutorial,
    Steve H

  • SteveH

    I’m pleased to say that after downloading your source code and comparing it with mine, I had found a typo and a missing “}”. All works now.

    Thanks!

  • StaffanS

    Works great, thnx for the tutorial! Including the additional comments how to close the keyboard when clicking Done, View or hitting Enter.

  • http://xQmail.eu magikMaker

    ok, that raps up my first night of iPhone coding… Thank you so much for the great tutorials! They were really helpful!

  • Michael

    I have followed you instructions carefully and I get the first view and can get the keyboard up and type in the text field. Pressing Done or the button does nothing. The action seems not to be actioned. Do I have some settings wrong? Do I have to join the various parts of the project together?

    Regards Michael

  • Josh

    Dosen’t work. The “-(IBAction) updateText (id) sender {” line gives me a “error: expected ‘{‘ before ‘(‘ token” error when I try to compile it. Help?

  • Paul

    Brandon,

    Thanks fot your great work, but… I seem to have the same problem as a few others posted here: when I connect the textbox to the file’s owner I only gt teh ‘view’ option. I’ve tried the different solutions mentioned above, but these don’t work for me. When I click ‘Build and run’ I get a lot of errors (expected specifier-qualifier-list before UITextfield), no declaration of property ‘txtName’ found in interface’ and so on.

    I’ve scanned my code 28 times, still the same mistake.

    What am I doing wrong?

    Regards,

    Paul

  • Paul

    Threw the non-working version away and did the tutorial again, now it works perfectly. That leaves me a bit worried/unsatisfied.

  • http://technotweets.com devang paliwal

    good job buddy :)

  • http://digg.com lolwat

    Thank you very much, I can’t believe how long I had to search the net that clearly demonstrated how to just connect things with the interface builder.

    Now I can really break some ground. >:]

  • http://ortuno2k.wordpress.com Juan

    I found this tutorial and will begin to type it in my Xcode.
    Thing is, that I don’t like to do things without understanding the “why” behind them.
    I want to learn to program for the iPhone & the Mac, but having a hard time doing so.
    Using obj-c to create a simple app for the console is completely different than using it on iPhone.
    I guess I gotta go back to trying…

  • Craig

    Wow!

    This is FANTASTIC! Coming from other programming environments I have been EXTREMELY shocked by the
    convoluted Apple approach to things. This really helps to
    boil this topic down to the nuts and bolts that you need to
    get something to work.

    Thank you.

  • Singh me A Song

    is there a way to execute , command line utilities using the buttons we build.

  • Pikkuroope

    Terminating due to uncaught exception :O

  • dude

    really nice job. this is the best step by step i’ve seen (out of about 30).

  • Maddog2k

    You rock! Thanks for the thorough tutorial! It explains and fills in critical gaps that Apple and other tutorials gloss over.

    My question: I tried the technique suggested above for causing the label to update when the keyboard’s Done key is pressed. I connecting the text field’s “Did End On Exit” event to the File’s Owner updateText action. When I do that, the Display button stops working – meaning the label doesn’t update when Display is clicked.

    If I unhook the text field from “Did End On Exit” the Display button starts working again. Why does one affect the other? They seem unrelated to me except that they call the same action.

    Is anyone else getting this and can anyone explain why and the correct way to do it??

    Thanks

  • John

    Your tutorial here is more detailed and clear than Apple’s.

    Thanks for helping me when they couldn’t.

  • Andrew

    Thanks alot, your tutorial really help me to understand

    Thankssss

  • Arun

    I have finally written my first iPhone app with this tutorial….really nice tutorial….other tutorials that i have been through was real greek and latin for me..this helped me a lot… :)

  • Alex

    im having a problem with the creatinga connection between the text field (txtName) and File’s owner the view –> File’s owner is already connected when i start a new project. but when i select the text field to begin to make the connection to “File’s Owner” it doesnt show up as a choice to connect it to. any ideas?

  • http://rdswebstudio.com Austin

    Alex I had the same problem as I am also just starting out. You need to right click on the “View” area and a block box will pop up. Then click on your text field. Now in the top right you will see the circle they talk about in the tutorial. Grab that and drag it to the black box and walla :)

  • Samuel

    Thank you for tutorial! I completed all the steps. However pressing Display button does nothing.
    I put the breakpoints inside
    -(IBAction) updateText:(id) sender {} function.
    Program flow never enters the function!

    In desperation I added another event: “Touch up inside”
    It worked.

    I experimented more. I think that
    “Touch up outside” event is not generated at all!?

    This may be bug in 3.1.2 simulator running under X10.6.2

    Any ideas or similar experiences?

  • Tiger

    My labels and such seem to refuse to connect to my code.

    I’ve created a view with a NIB called “Search Results NIB”, and it has a label on it. I connected to Files Owner to Search_Results_View (the view controller), connected the View I created to the File’s Owner, and then connected label I created to the File’s Owner (with a variable named “filterBy”).

    So then in my app, when the user selects an element in a table, it creates a “Search Results View” and pushes it onto the view controller like so:

    Search_Results_View *controller = [[Search_Results_View alloc] initWithNibName:@”Search Results NIB” bundle:[NSBundle mainBundle]];

    controller.title = [NSString stringWithFormat:@"Poh's %@",[[tableData objectAtIndex:0] objectAtIndex:[indexPath indexAtPosition:1]]];

    controller.filterBy.text = @”Hello World”;

    appDelegate.vcRecipesScreen.vcResults = controller;

    [controller release];

    My issue is that the text on the label just won’t change! In fact, when I set break-points to see what is going on, filterBy is set to 0×0, which means it isn’t even being allocated…

    So what is going on? Please help, I’m so confused…

  • Tiger

    Whoops – discovered my own problem…

    I was trying to set things before “viewDidLoad” had actually occurred…

    How silly

  • Eric

    Excellent stuff, Brandon, thanks so much!

    I am VERY new to the Mac and thus am making all sorts of noob mistakes, one of them being:

    I dragged Xcode to the desktop and now, boom, it doesn’t work.

    This problem needs to be resolved before I can go further, any ideas?

    Thanks again for the great walkthroughs!

  • TD

    Thanks for the tutorial.

    I don’t know if this was a problem with me or something that has changed with the SDK, but I had to manually link the “view” to get this tutorial to work.

    In the Interface Builder, under Connections, drag from the circle to the right of “view” to “File’s Owner” and select “view”.

    Prior to doing that, the app would start up and instantly close. It was only by comparing what I had to the downloaded xib file that I found the issue.

  • http://www.teknotica.co.uk Silvia Rebelo

    Hi Brandom!

    Thanks for the tutorials, they are really nice explained and run smoothly. Thanks a lot!

    ^^

  • K

    I had the same “view” connection issues as many. A solution to this problem is the following:

    - Highlight “File’s Owner” in Interface Builder
    - Click on “File->Read Class Files…” from the menu bar
    - Navigate to your view controller header file (ViewBasedViewController.h) and click “Open”

    You can now make your connections as the tutorial describes

    Thanks for the tutorials Brandon!

  • Craig

    When I run this example my textfield fills the entire window at runtime (but looks fine in IB). Any thing obvious I’m missing?

  • Craig

    Should have spent another 2 minutes looking at it before I posted. Turns out I didn’t have the TextField’s delegate connection hooked up to File’s Owner. So my next question is: Could someone explain that behavior?

  • http://www.gatoblanko.net brin k.

    Nice tutorial. Helpful. Thank u.

  • KTs

    Hi,
    Great tutorial, Bradon :)
    In this Application, I’m trying to find how to write a code or use events to quit an application.
    Example: I make a button with name:”Quit”, when you click, it quit your current application and return to applications view. Can you show me how to do it?
    Thanks.
    KTs

  • Tihomir

    Thanks man, great tutorials!

  • Tammy

    ViewBasedViewController.m

    Please only RELEASE if you have ALLOC.

    If your if-statement is true… you don’t ALLOC…. but you *STILL* free the memory.

    Ugh.

  • Chuck

    The tutorial seems to work and it builds fine. The iPhone simulator comes up and I click in side the Name box and click out my name.
    But there’s no way to hit the Display button now. The keyboard stays up and on top of the view with my Display button and cannot be dismissed, even with the Done button on the keyboard itself! Clicking on the Done button doesn’t do anything. Should there be more code that needs to be addd to the Done button? Since the Done button was created automatically, it’s function should also work automatically, right?
    Well, … I was understanding the tutorial up to that point. I read some of the comments above, but it was clear that their level of programming was way ahead of the level of this tutorial, so I can’t make any sense of it.

    Thanks!

  • http://bonfx.com/8-great-resources-on-how-to-make-your-first-iphone-app/ 8 great resources on how to make your first iPhone app

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

  • David

    Great tutorials so far. I just have a couple of things so I’ll start easiest first :P
    KTs – It is possible to quit but apple hate having a quit button. It looks like the application has just crashed. I was told that it is possible to be done. I think, don’t quote me on this, call quit(0) is what will make the app quit.
    Next problem. I’ve written the code for this tutorial myself by hand and downloaded the source code from here. Neither compile properly. There are 3 identical issues – ‘didRecieveMemoryWarning’ undeclared (first use in this function) Expected ‘;’ before ‘{‘ token Expected declaration or statement at end of input.
    Can anyone help on these?

    Thanks

  • Hong Duc

    Hi Brandon,
    Thanks for the great tutorial on iPhone platform. This is really a great help for people who get familiar to this platform for the first time.
    I follow your instructions very carefully and it works like a charm, but now I’m dealing with the “hide the keyboard automatically”
    problem. I tried your instruction, which is add one line
    [txtName resignFirstResponder]; and it works fine.
    But the problem is, I want to experiment another way to do this, which is to make a delegate like many people had said before I came here
    .So I add something like this:

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

    and in the Interface Builder view, I chose the Textfield, click and drag the circle of the delegate to the File’s owner. But the keyboard still doesn’t hide after I click Display. So can you help me with this? or did I miss something in the .h file. From my experience, I think I need to declare something in the .h which it can be recognized in the .m file ( I used to work code with C++ so I think these are the same ). Can you help me

  • Meito

    Again, this doesn’t work on 3.1.2 simulator :( , i don’t even have the ViewBasedViewController.h, i think i have to found a new tutorial under this simulator, if you have a link to this kind of tutorials i will thank you a lot, i have to develop for 3gs cell phone, sorry

  • Jayomat

    @Hong Duc:

    Xcode : Create an IBAction method in our Controller class that will cause the UITextField to release his grab of the keyboard. Put the following line in your .h file:

    -(IBAction)textFieldDoneEditing:(id)sender;

    IB : Connect the UITextField’s DidEndOnExit event to our new IBAction method
    IB : Set the Keyboard>Type property of the UITextField to Done
    Xcode: put this in your .m file:

    -(IBAction)textFieldDoneEditing:(id)sender{
    [sender resignFirstResponder];
    }

    In interface Builder, you need to connect your Did End On Exit event to this method.

    gl

  • derak

    Great! Thank you. This was very helpful.

  • Sylvain

    You use @synthesize lblHello.

    But then you use : “lblHello.text = text” and not “self.lblHello.text = text”.
    “self” is not mandatory if we want to call the property ? else we call the ivar ?

    Thank you for your help.

  • http://bw.org/ Bill Weinman

    @Joyomat — Actually, you don’t need another method. Just connect the UITextField’s done event to the existing updateText method and put the [sender resignFirstResponder] in there. This has the added benefit of making the Done key update the UILabel.

    - (IBAction)updateText:(id)sender {
            if([txtName.text length] == 0) {
                    lblHello.text = @"Please enter your name";
            } else {
                    lblHello.text = [[NSString alloc] initWithFormat:@"Hello %@!", txtName.text];
            }
            [sender resignFirstResponder];
    }
    
  • James

    I really wish you could print this. Only the first printed page has any actual content on it. Is there some script that “lazy loads” the rest of the content as you scroll, that may be interfering with the printable content?

  • Dan

    Hi,

    thank you for the tutorial. it’s great and easy to follow.
    unfortunately i have a little problem and after reading the comments i cannot find the solution or i just cannot identify my problem as having been solved nor asked so far.
    well here we go:

    after finishing the coding and implemntig the view i saved the code and the view and i click “Build and run”. The iphone simulator starts but nothing happens. it just displays the iphone home screen…and when i click the app it starts and quits again…

    can anyone haelp me? i bet it’s a simple problem.

    thx so much
    greets
    dan

  • http://shaiperednik.com/2010/07/iphone-programming-tutorial-%e2%80%93-local-notifications/ iPhone Programming Tutorial – Local Notifications » Shai Perednik.com

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

  • Noah

    Check all your capitalization on the code, just to make sure there aren’t any uncaught typos. Also check your connections with IB. Is your File’s owner connected to the view? This has happened to me before, causing the same problem.

  • http://www.dispersiontechgroup.com/ Bhaktavatsalam

    Concise, simple and straight forward. Thanks a ton.

  • Neeeol

    I have the same problem, Chuck. I also noticed that in the screen shots, the keyboard doesn’t disappear.

    I would have expected that when the user tapped Done the keyboard would disappear, but apparently not. This must be one of those secret handshake situations where no one tells you the key detail because everyone thinks you already know it.

    In my case, I want to bring up a number pad, but no matter what I select, no button for “Done” or “Go” or anything else even gets displayed.

  • http://blog.wooh.hu Adam PAPAI

    This tutorial works like charm :) Everything is extra clear and working out of the box without any compiler error :)

    Keep up with the good work :)

  • http://www.uwsp.edu/ATHLETICS/mbb/05-06/roster.htm Team Roster

    You you could edit the webpage name title iPhone Programming Tutorial – Connecting Code to An Interface | iCodeBlog to something more specific for your content you create. I loved the blog post nevertheless.

  • http://tinyurl.com/26s2zhw Elisha

    Nice posting… Excellent.. Good job…

  • http://www.erazer.org/iphone-programming-hello-world/ iPhone programming hello world | developer in Ukraine

    [...] For example, here is a very good way to start your acquaintance with the subject: iPhone Programming Tutorial [...]

  • Dhananjaya

    its very nice tutorial

  • http://www.worldoftrade.com/ Rolex Cellini

    Your work has always been a great source of inspiration for me. I refer you blog to many of my friends as well.

    Thanks for sharing knowledge..

  • Artrozzz

    Hey, sorry to bother you but Im just starting to learn all this, and I do exactly as it posted on your tutorial but my App is not opening in the simulator. My Sim version is 4.2. Did they change something in there?

  • http://Trinifieds.com Chanders

    Hey guys, I just wanted to say what a great site this is. I am trying this exercise with the latest Xcode 3.2.4 with 4.2 and like the above poster, the application starts but then returns to the springboard. Can anyone shed some light on this?

    Thanks!

  • http://Trinifieds.com Chanders

    Seems “Is your File’s owner connected to the view?” was the problem.

    Thanks!

  • http://www.digital-canopy.com Brian Kuyath

    Another great tutorial! Thanks!

  • Mike m

    Great tutorial! This is exactly what I needed to dip my toe into iPhone dev. Thanks Brandon!

  • Ben

    That is exactly the problem I had. Connect the view to the file’s owner and it won’t crash.

  • Jeff Bonta

    Nice tutorial, but I can’t get past section 2 on connecting the text field. I selected the text field and drew the blue line from the New Referencing Outlet to the Files Owner. When I release it, my only choice is View. I am using xcode and IB 3.2.5. Am I missing some subtle action?

    I came to this tutorial because I have tried others that update a text field or label, and they are all failing on me too. All tutorials were written in 2008, so perhaps things have been updated and old ways don’t work. The problem I have with the other tutorials is that when I run the app and hit a breakpoint on the line that is updating the textfield or label, the content of the textfield/label is x0000 (i.e. when I mouse over the variable). Consequently, nothing gets written to the textfield/label, but there is also no indication of the app failing.

    Any help on either of these issues would be most appreciated. I am pretty much stuck.