XCode Tutorial Practice 2: Buttons, Textboxes and Handling User Interaction

Updated Oct 3 2013: This tutorial is compatible with XCode 5 AND XCode 4!

We’re taking a practical approach to learning iOS programming. This means lots of hands on work and practice!
In order to benefit the most from these lessons, you should open XCode and try to follow along.

This is part 6 of the lesson plan. Click here for the entire Learning Plan.

In this tutorial, we’re going to explore some additional UIElements and how to handle user interaction!

I highly recommend that you follow along on your own computer to get the most out of these lessons.

We’re going to start a brand new single-view project. If you forgot how to do this, please refer to the tutorial on creating your first XCode project.

Adding a Button to the View

Let’s start with adding a UILabel, UITextField and UIbutton to our view!

First let’s go into Interface Builder to edit Main.storyboard. Click on that file now in the Navigator.
If you’re using XCode 4, your storyboard file may be named differently.

The editor area is going to change to Interface Builder.

We’re going to add a UILabel to the view just like in our Hello World demo. Search for “UILabel” in the Library pane in the lower right hand corner and drag the UILabel onto your view.

Next, repeat the same steps but this time, search for “UITextField” and drag and drop that element onto your view.

Next, repeat the same steps but this time, search for “UIButton” and drag and drop that element onto your view.

You should end up with a view with a label, textfield and button.

UILabel, UITextfield and UIButton in Interface Builder

Let’s put some text on this button through the property inspector on the right hand side. Since we’re going to make the button change the text of the label, let’s add the text “Switch Text” to our button. You can also take this opportunity to widen your UIButton and UILabel elements a little bit by adjusting it in Interface Builder.

Changing UIButton text

Exposing UIElements to the ViewController

ViewController is the class that manages the view so naturally, it’s going to be the place we add the code to handle the button click. However, before we can do that, the ViewController needs to have references to the UILabel and the UIButton that we added to the view; otherwise, how does it know about them?

Interface Builder has an easy drag-and-drop way for us to create the properties in our ViewController and also assign the UIElements we create in Interface Builder to these properties of the ViewController. This way, our ViewController will have references to these UIElements and it can do things with them!

First, click the ViewController.xib file in your navigator so that you see the Interface Builder view.

Next, you need to click an icon called the “Assistant Editor” located in the upper right corner of XCode. It kinda looks like a butler icon. Check the screenshot below.

Assistant Editor Button

Clicking that screen will give you a split window view.
On the left hand side, you’ll have the Interface Builder view of ViewController.xib.
On the right hand side, you should be looking at ViewController.h.

If you’re not, you can change it like in the screenshot below.

Change right pane

Once you have ViewController.xib on the left hand side and ViewController.h showing on the right hand side, all you have to do is hold down “control” on your keyboard, click your UILabel on the left hand side and drag it over to the right hand side, and drop it on an empty line under “@interface ViewController : UIViewController”.

As you’re dragging, you should see a blue line follow your mouse like this screenshot:

Adding IBOutlets From Interface Builder

This will pop-up a little dialog asking you to name the property that it’s about to create for you.
Type in “helloLabel” and click “Connect”

Interface Builder Adding IBOutlet Dialog

The end result is that your ViewController.h will have this code:

Next, you’re going to do this for the UITextField element. So hold down “control” on your keyboard, click your UITextField on the left hand side and drag it over to the right hand side, and drop it on an empty line under the label property. I named this property “customTextField”.

Now your ViewController.h will have this code:

Next, you’re going to do this for the UIButton element. So hold down “control” on your keyboard, click your UIButton on the left hand side and drag it over to the right hand side, and drop it on an empty line under “@property (strong, nonatomic) IBOutlet UILabel *helloLabel;”. I named this property “clickyButton”.

Now your ViewController.h will have this code:

Great! Now you’ve just created three properties in the ViewController class that reference the three UIElements in your ViewController.xib. This allows you to access the UILabel, UITextField and UIButton from your code in the ViewController object.

Let’s try that now; go to ViewController.m
(You can go back into single view now)

XCode Single View Button

In the method “viewDidLoad”, we’re going to add some code to change the text of the UILabel and the UIButton.

Add the below two lines into your viewDidLoad method so that it looks like this:

If you run your app now, you’ll see this (widen your UILabel in Interface Builder if your text is cropped):

iOS Simulator - UIElements on screen

Handling Button Clicks

To handle a button click, we need a method in ViewController.m that the contains code we want to be executed when the button is clicked. Then we connect this method to the button click event of the UIButton in our view.

Interface Builder provides an easy drag and drop way to create this method and all we need to do is fill in the code.

So once again, turn on Assistant Editor view where we have two panes. The left hand side should have ViewController.xib and the right hand side should show ViewController.m.

When we were creating properties, we had ViewController.h on the right pane, but this time, we’re creating a method to handle the button click so we want ViewController.m on the right hand side.

If you have trouble changing the file on the right hand side, click the button circled in this screenshot:

Change right pane

Once you have both the xib file and the .m file visible, hold down “control” on your keyboard, click and drag the UIButton in the view over to the right hand side and drop it on an empty line just before “@end”. I named my method “handleButtonClick”.

Add IBAction From Interface Builder

You’ll end up with a new method created in ViewController.m that looks like this:

Now whenever the button is clicked, it will execute the code in this method!

Changing The Label Text

Next, let’s change the text of the label to whatever is in the textfield when the Clicky button is clicked.

In the “handleButtonClick” method that we created previously, we’re going to add the single line of code below.
Also, we’re going to add a method below “handleButtonClick”, called “touchesBegan”.
Follow the code sample below:

Now if you run the app, you’ll be able to type in some text into the textfield, tap outside to dismiss the keyboard and then click the button to change the Hello label text.

iPhone Simulator - Change Text via Button Click

In the next lesson, we’ll do a recap on what we did in this practice. You’re making great progress so far!

Click here to go to the next lesson now!

Frequently Asked Questions

If you have a question related to this tutorial or need me to clarify something, please ask in the comments below and I’ll update this FAQ section for everyone’s benefit.

214 thoughts on “XCode Tutorial Practice 2: Buttons, Textboxes and Handling User Interaction”

  1. hey brooo, i have a doubt. i want the button’s text should get from the database.same name which is used stored in a specific row in a database.How can i get the same text.If the admin change the name in database its automatically update required in button text also

    • Hey Saifu, unfortunately that’s way beyond the scope of a beginner’s tutorial like this! It would involve a setup where your app makes a request to a web service sitting on a server and that web service connects to the database to retrieve that information and then that web service returns that information to the app. You would have to build the web service yourself too. I demonstrate how to do this in my Toolbox course but I recommend to finish the Beginner course before tackling the Toolbox course.

  2. For the main storyboard, what is the difference between the navigation, detail and the master templates on the main story board and what should I use them for?

  3. Using Xcode 6. So far several differences noticed. After linking the label, text box, and button to ViewController.h editor, I run the simulator and am shown this breakpoint. I was able to run the simulator once this far in the tutorial. I’m pretty sure I’ve followed your steps exactly this second time around. I had to close everything and start over and now am unable to see my progress on the simulator. I hope you can see my screenshot attached to this comment. Also, I tried to edit this comment by adding a better screenshot, but the comment editor for this page doesn’t allow the option to delete current attached screenshot and use a different screenshot. Please help.

  4. Every time I try to control click and drag the Change Text button to the ViewController.h file it doesn’t connect. Any suggestions?

  5. Yay, I smell some progress…! this is the furthest I got this far, never been this far before using a beginer guide book.

  6. return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));

    ^ This is what I get when I launch the app after putting the codes to make it all work (before adding the code for the keyboard to hide). The app pauses and takes me back to that Xcode screen. What to do?

  7. this is the error message

    2014-09-13 00:02:29.886 App2[2005:60b] *** Terminating app due to uncaught exception ‘NSUnknownKeyException’, reason: ‘[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key Button1.’

    I don’t understand the reference to “Button1” because I have used the find function and this is not present in any of the files

  8. Hi Chris. I’m a complete beginner, but found your tutorials really interesting. Unfortunately I can’t get the Hello World App to run. I can run the app with the UI components added alone and interact with them, but as soon as I assign the properties within viewcontroller.h, I am faced with error messages. Any idea what I am doing wrong? I tried copying the code from your tutorial notes, but the same errors were generated. Any help would be much appreciated

  9. Chris,

    Awesome tutorials, beginner here, and I am learning quite a bit! I’m stuck on approx. 6:06 of part 6 on your videos. Once I click run it pops up open with the debug screen at the bottom and doesn’t open up the IOS simulator. Where would my error have been if i’ve followed every step since then?

  10. HEy chris ching wonderful work dude…. thank you so much for wonderful tutorial …. hope you will share more knowledge with us..!!! thanks from @Parth Darji

  11. hey Chris would you mind having a look at this issue , It has been saying use of undeclared identifier ‘self’ thanks

  12. Hi Chris, I am so happy about your tutorials. It is very effective learning mode for an IOS beginner like me. I am a ColdFusion developer by profession and iOS is something I have been eager to learn since I was able to afford my Macbook.

    My question is, I am trying to change the width of the label dynamically as the text size change. To give a start I got this code from StackOverflow (tweaking done from my end) and put it in my viewDidLoad block so that I put a long text and place a narrow label still onload I see my text completely. But I dont see any error nor the code working.

    My code at viewDidLoad:

    NSString *nuTxt=@”Hello I can Change”;

    CGFloat width;
    if ([[UIDevice currentDevice].systemVersion floatValue] < 7.0)
    {
    width = [nuTxt sizeWithFont:[UIFont fontWithName:@"Helvetica" size:16.0 ]].width;
    }
    else
    {
    width = ceil([nuTxt sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:16.0]}].width);
    }
    self.lblTxt.frame = CGRectMake(107,112, width,21);
    self.lblTxt.text=nuTxt;

    Please help.

    Regards,
    Yoosaf Abdulla

  13. im re using files, with button action click… It works on previous project but when i reloaded them onto the new project the button click doesn’t work. I was reading some comments and you mention to reconnect them with ..h file again… Is there ashortcut to reconnecting all my buttons? Because I have a lot of view controllers

  14. I wanted to reuse my .h and .m files with already IBACTION in it. I already did the “hold down “control” on your keyboard, click and drag the UIButton in the view over to the right hand side and drop it on an empty line just before “@end”.” in the previous project. Now, I added this file to a new Project and the button doesn’t work. Do I need to keep doing that hold down stuff? is there like a shorter way to do it. I have a lot of ViewController…

  15. Hi, I am newbie to iOS app development. I am using XCode 5.1 and C-objective language to develop a very basic application in which user can copy a text and paste it into a text box.
    So the aim is that when user taps on a text may be a label, he/she gets an option to copy and when clicks in a text box an option to paste the copied text should be present.
    Please help.

    • In your ViewController.h file, you mixed up the two labels (you put *customTextField as a UIButton, and *customTextButton as a UITextField)

  16. Ok, so when I drag the button into the assistant editor, then name it, it gives the option to connect, however once I do it connect stops working and it’ll only do so if I’m using action or outlet collection under connection. What am I doing wrong? 🙁

  17. My app keeps on crashing when I try to text the “touchesBegan” property but when I get rid of it, it is fine. Can you help me debug this problem?

  18. I am using the latest version of Xcode, and I do not see any file that says .xib! Anyone know what the name is in the latest version of Xcode?

  19. hi chris! just wanted to let you know that i got this working, like many other people, and this is awesome. I’ve been looking all around about where to start in the iOS programming world and i am so happy to have found this tutorial series! thank you so much, and me and my friends will be waiting for more as we become more familiar with programming! thank you!

  20. Hi Chris,

    I need your help please. I am doing a really basic example right now and there seems to be a problem of displaying the complete text in the IOS simulator.

    For eg.

    I wanted to display Score : 50 in the simulator but it only shows Scor…..

    The rest of the text is not being displayed.

    Please guide me on how to show the complete text.

    Thanks!

  21. Hi Chris,
    Today I am starting to work on button click and Google for some tutorial or help. Found this post and go stepwise and finally understand the things.
    Thanks a lot.

    • Hey Kevin, in the pane in the lower right hand corner, there’re actually a couple of icons that represent “tabs”. Make sure you have the “objects” tab selected.

  22. Hi Chris! You’re amazing! I am glad that I landed on your site. Following your lessons I could recall my C++ & Java programming memories from 13 years ago. I will keep following your lessons. Your site is gonna be my bible now. By the way! I did a little bit extra to the BlankDemo… I put two more buttons that change the color of the label text.

    – (IBAction)changeRedLabel:(id)sender {

    self.helloLabel.textColor = UIColor.redColor;

    }

    – (IBAction)changeBlueLabel:(id)sender {

    self.helloLabel.textColor = UIColor.blueColor;

    }

    I am so happy they work!

    Thanks for the lessons!

  23. hi sir

    showing error “no visible @interface” for”UIview” declared the selector ‘setTitle:forstate’

    for “[self.clickyButton setTitle:@”Clicky” forState:UIControlStateNormal];}”

    • Hey Ritesh, this means that your property “clickyButton” is actually connected to something other than a UIButton! So that’s why when you try to “setTitle” on it, it doesn’t recognize that method because what you have clickyButton connected to isn’t a button!

      When you click and dragged it over to the .H, you may have dragged and connected the wrong thing.

      You can go into your storyboard, right click the view and see if you can find the one you connected. Then click the “x” to break the connection with the “clickyButton” property.

      Then you can try to re-connect the button!

      • YOU KEEP SAYING THIS ANSWER SO THAT SAME PROBLEM EVERYONE IS ASKING ABOUT! JUST ANSWER IT FOLLOWING THAT LINK DONT HELP THE PROBLEM SRY FOR CAPS BUTTON STUCK

          • What was wrong is that in the beginning of your tutorial when dropping and dragging your buttons people need to realize that they need to change the UIbuttons to strong and no atomic that’s the problem! Took me a minute to look at your screen and see the coding difference. My settings were set to weak and when I changed it everything worked! Thx and sry for caps earlier my keyboard is broke and well it works when it wants to

  24. Help, I have gone through the process and have reviewed my code and cannot fix this. Is there something wring with the delegate.h/m? What is the issue. The problem starts only when I press the button, the rest works. Thank you a lot.

    Ricky

  25. Strangely I am following it exactly but it didn’t turn out to be successful. I mean there is no error, only a few bug:

    1. when I change the text and clicked, the label display none. Strange, because I put exactly

    self.helloLabel.text = self.customTextField.text;

    when I change to self.helloLabel.text = @”dummy text”; then it worked!

    Do you know why?

    2. Also when I hit the button, the keyboard doesn’t dismiss. The same when I click all area, it doesn’t affect the keyboard.

    Thanks in advance if anyone can show me my error

  26. Hi Chris,

    Thanks for the tutorials.

    I’m halfway on finishing the exercise/project and I tried to “run” app. The Simulator shows nothing and Xcode 5 gave me this code: “return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])) Thread 1: signal SIGABRT;”

    What does this mean???

      • It’s just this: “return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])) Thread 1: signal SIGABRT;”

        Everytime I run, that code shows up in the debug navigator and highlighted in green..

      • 2014-06-06 21:45:15.890 UserInteraction[7178:60b] *** Terminating app due to uncaught exception ‘NSUnknownKeyException’, reason: ‘[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key ChangeText.’

        I think that’s the detailed error that you mean..I saw it in debug navigator…

  27. Hi Chris,

    I was curious if you could explain how to, instead of on a touch event outside the keyboard, just how one would get the keyboard to dismiss on pressing the ‘return’ key.

  28. Hi Chris,
    I have done above lesson. But i have a problem when i clicked button: label don’t still format alignment. I can’t do it. Please help me!
    Thanks!

    • Hello Thien, I suspect that your label property is not connected to the label element of your storyboard.
      In your .H file, do you see a little filled in gray circle to the left of your label property? If not, that means that the property is not connected and you’ll have to connect it to the label element in your storyboard!

      • Thanks Chris, I had solved. Because i don’t set alignment for it in buttonClicked();
        first, i think i declared property of label “weak” but not. you can explain “weak” and “strong”. have a good day!

  29. Hi Chris, I can’t drag my button over to the right hand side, and drop it on an empty line under “@interface ViewController : UIViewController”. Is there any alternative way to do so?
    Because I am using MacInCloud in my windows with normal keyboard.

    • Hello Tienny,

      Yes! You can manually type out the property IBOutlet in the .H file.
      Then in your storyboard, right click the Button and in the dialog that appears, you’ll see a line that says “referencing outlet”. There’s a tiny circle to the right of that. Just click and drag that circle down to the yellow circle in the screenshot.

      Then another dialog will popup and you can select the IBOutlet that you manually typed out.

  30. Hi Chris

    – (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    //[self.view resignFirstResponder];

    [self.ClickMeButton resignFirstResponder];

    }

    ResingFirst Responder not working in my Case

    Thanks
    Nilesh

  31. Hey Chris, I’m sorry I am sure you’re sick of all of my questions but I was wondering In the picture below is it supposed to be red or does that mean something is missing? Thank you.

  32. Hey Chris, I have learned a lot from this tutorial thank you again. In this tutorial you had us go into main.m and type this code ”

    – (void)viewDidLoad
    {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.helloLabel.text = @”default text”;

    [self.clickyButton setTitle:@”Clicky” forState:UIControlStateNormal];
    }” If I wanted to rather than set helloLabel to a color and than make it so that clickyButton would make that color change every time I clicked how would I do that? I’m guessing that i have to change the helloLabel bit to:”
    self.helloLabel.COLOR = @”100;” but how exactly? Thanks.

    • Hey Chad, in the button click handler method, (where it set’s the text for the label), you can set the color property of the label to a UIColor.

      For example:
      self.helloLabel.textColor = [UIColor redColor];

  33. Hi Chris,

    First let me say these are great tutorials. I have no real programming experience but I’ve been interested in learning how to make iPhone apps for a while. So your tutorials are ideal for me and I’m really enjoying them.

    I have a problem that I hope you can help with, if you have the time…….I have created the property in viewcontroller.h

    @property (strong, nonatomic) IBOutlet UITextField *customTextField;

    (it’s worth pointing out in my Xcode it automatically said “weak” so I manually changed to “strong”)

    and in viewcontroller.m I have the following code

    – (IBAction)changeTextClick:(id)sender {
    NSString *customText = customTextField.text;
    self.helloLabel.text = customText;

    But I get an error message saying that I am trying to use an undeclared identifier “customTextField”……Xcode is suggesting I change it to” _customTextField”but that doesn’t work.

    Any ideas? Hopefully it’s not something really obvious and I’m being stupid! Any help much appreciated.

    I’m using Xcode 5.

    • Hey Chris…..sorry for wasting your time if you read this….it was something stupid! I didn’t put “self.” in front of customTextField. D’oh!

      I’m now getting an error
      *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[ViewController changeTextButton:]: unrecognized selector sent to instance 0x8d86150’

      I’m working through on your FAQ page on this one….I don’t see where the issue is with changeTextButton…..I’ve set it up in the viewcontroller.h file exactly as it showed in the video. I’ll keep looking and see if I can figure it out!

      • All sorted! I had linked the text field to the changeTextField action instead of the button. D’oh again!

        I’m probably learning more about how it all works by my mistakes than by what I get right 🙂

  34. I’m sorry Chris but I don’t remember what was wrong with it because I accidentally deleted it thinking it was one of my other projects. I hope it won’t cause you any trouble.???

  35. Why do you make the button an outlet? Isn’t it just supposed to be an action since the button’s properties aren’t changing?

    • Yup, if you don’t need to reference it or modify it’s properties, you don’t have to make it an outlet. I wanted to show how to make it an outlet in this video though. Thanks for watching and commenting!

Leave a Comment

Share
Tweet
Pin