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

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.

213 Comments

  1. You explain things really well, but I have Xcode 10 and everything is different, so even though I’m trying to follow instructions, I can’t get the same result. For instance, the UIViewControllerh looks TOTALLY different than yours, so I’m putting the outlets in the wrong places because I’m just guessing.
    I really wish I could follow these lessons, because it’s clear that you’re a good teacher πŸ™

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

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

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

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

  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!

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

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

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

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

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

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

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

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

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

  29. Hi Chris

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

    //[self.view resignFirstResponder];

    [self.ClickMeButton resignFirstResponder];

    }

    ResingFirst Responder not working in my Case

    Thanks
    Nilesh

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

  31. 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];

  32. 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 πŸ™‚

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

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

  35. Hi!
    when i drag the label inn to the view controller.h it says weak insted of strong as in yours. This is what i get when i type it inn.
    @property (weak, nonatomic) IBOutlet UILabel *helloLabel;

    is that a problem?

  36. Thank you so much for this! It was working for a while but than it keeps throwing out this error whats wrong? “2014-04-15 17:26:42.369 Learning Button[28599:a0b] *** Terminating app due to uncaught exception ‘NSUnknownKeyException’, reason: ‘[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key handleButtonClick.’
    *** First throw call stack:
    (
    0 CoreFoundation 0x017395e4 __exceptionPreprocess + 180
    1 libobjc.A.dylib 0x014bc8b6 objc_exception_throw + 44
    2 CoreFoundation 0x017c96a1 -[NSException raise] + 17
    3 Foundation 0x0117d9ee -[NSObject(NSKeyValueCoding) setValue:forUndefinedKey:] + 282
    4 Foundation 0x010e9cfb _NSSetUsingKeyValueSetter + 88
    5 Foundation 0x010e9253 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 267
    6 Foundation 0x0114b70a -[NSObject(NSKeyValueCoding) setValue:forKeyPath:] + 412
    7 UIKit 0x004cca15 -[UIRuntimeOutletConnection connect] + 106
    8 libobjc.A.dylib 0x014ce7d2 -[NSObject performSelector:] + 62
    9 CoreFoundation 0x01734b6a -[NSArray makeObjectsPerformSelector:] + 314
    10 UIKit 0x004cb56e -[UINib instantiateWithOwner:options:] + 1417
    11 UIKit 0x0033d605 -[UIViewController _loadViewFromNibNamed:bundle:] + 280
    12 UIKit 0x0033ddad -[UIViewController loadView] + 302
    13 UIKit 0x0033e0ae -[UIViewController loadViewIfRequired] + 78
    14 UIKit 0x0033e5b4 -[UIViewController view] + 35
    15 UIKit 0x002669fd -[UIWindow addRootViewControllerViewIfPossible] + 66
    16 UIKit 0x00266d97 -[UIWindow _setHidden:forced:] + 312
    17 UIKit 0x0026702d -[UIWindow _orderFrontWithoutMakingKey] + 49
    18 UIKit 0x0027189a -[UIWindow makeKeyAndVisible] + 65
    19 UIKit 0x00224cd0 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1851
    20 UIKit 0x002293a8 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 824
    21 UIKit 0x0023d87c -[UIApplication handleEvent:withNewEvent:] + 3447
    22 UIKit 0x0023dde9 -[UIApplication sendEvent:] + 85
    23 UIKit 0x0022b025 _UIApplicationHandleEvent + 736
    24 GraphicsServices 0x036902f6 _PurpleEventCallback + 776
    25 GraphicsServices 0x0368fe01 PurpleEventCallback + 46
    26 CoreFoundation 0x016b4d65 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 53
    27 CoreFoundation 0x016b4a9b __CFRunLoopDoSource1 + 523
    28 CoreFoundation 0x016df77c __CFRunLoopRun + 2156
    29 CoreFoundation 0x016deac3 CFRunLoopRunSpecific + 467
    30 CoreFoundation 0x016de8db CFRunLoopRunInMode + 123
    31 UIKit 0x00228add -[UIApplication _run] + 840
    32 UIKit 0x0022ad3b UIApplicationMain + 1225
    33 Learning Button 0x00002e9d main + 141
    34 libdyld.dylib 0x01d75725 start + 0
    )
    libc++abi.dylib: terminating with uncaught exception of type NSException
    (lldb) ”

    Help would be great

    • Hey Chad! Thanks for following the tutorial! This error usually indicates that there’s a storyboard UIElement that’s connected to a property that doesn’t exist anymore. This can occur if you connected it to a property and then removed the property from the .H file.

      In order to fix it, go into your storyboard and right click each element to check the connections to the properties and “break” any connections to properties that don’t exist in your .H file anymore by clicking the little “x” beside each bad connection!

  37. First, I want to thank you SO SO SO SO much because of all your help. Concepts that i though i would never understand I am getting because of your tutorials. But, I have one question. I am pretty sure i have followed this video because I have watched it like ten times, but every time I run it it just exits out ands goes to a screen that has three threads. Can you help me?

  38. Hi Chris,
    Sending you a screenshot of where I am stuck. I tried to run the app after creating the button, text and label properties in .m controller. it succeeded but I can’t see the screen. Its black. It shows some apple thread issue on the screen. Is that the issue?
    Please help.
    Thanks

  39. Hey Chris,

    So I did everything up until the “Handling Button Clicks” section, but when I put the code in the ViewDidLoad method and tried to run a Demo, it said Build Failed. It returned these two errors. I’ve checked and checked, but I can’t seem to find what I’m doing wrong. Any ideas? Thanks for the help!

    Best,
    Britt

    • Hey Britt, it looks like some of your UIElements are incorrect! At the top of your file there, the “helloLabel” should be a UILabel type instead of UIView.
      The customTextField should be UITextField type and the clickyButton should be UIButton.

      However, my suggestion would be to delete all of those IBOutlet properties and then go into your storyboard and right click each element and click the “x” beside the referencing outlet to break the connection for each outlet.

      And then reconnect them all using the ctrl-click technique, this time making sure that you’re adding them to xyzviewcontroller.H and not the .M file.

      Let me know if that works!

  40. Hi Chris,

    Thanks for the amazing tutorials, I’ve been scanning the web for a starting point for ages, and your tutorials are perfect.

    I’ve got a minor issue with this – my text is updating when i deactivate the keyboard by clicking offscreen instead of when i click on the button. any ideas?

    Matt

      • yep – its as follows:

        – (IBAction)handleButtonClick:(id)sender

        {

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

        }

        • Hey Matt, i have a feeling that you may have connected that method to one of the UITextField events rather than the button?

          Take a look at the screenshot below.. you can click your textfield in the storyboard and then click the connections tab like in the screenshot and see if the method is connected to any of the UITextField events.

          In particular, see if the method is connected to any of the “did finish editing” type of events.Hope that helps!

      • – (IBAction)handleButtonClick:(id)sender

        {

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

        }

        it goes like this right?

        cheers,
        Matt

  41. Hello Chris, quick question on this video. It’s more of a speculative question rather than something I don’t understand. Here’s what i’m looking at:

    NSString *customtext = self.textfield.text;
    self.label.text = customtext;

    I understand that here we are simply creating a variable which stores the text from the textfield, and then passing that text from the variable into the label. I’m wondering if the order in which we code it, matters? By the order I mean which side of the ‘=’ symbol each piece of code is on.

    Like if you write:

    self.textfield.text = NSString *customtext;
    customtext = self.label.text

    Would the method still execute the code in the same way?

    Thanks, Ehsun

    • Ok so I tried it and it doesn’t work. The build succeeds but pressing the button does not change the text. I don’t quite understand why.

      I am trying to make sense of why the order of the coding is so particular:

      NSString *customtext = self.textfield.text;
      self.label.text = customtext;

      Would I be right in saying that whatever is on the left side of the ‘=’ holds whatever is on the right? Like the variable in the first statement holds the text property of the textfield. Then on the second statement, the text property of the label holds the variable which we created in the first statement?

      • Hey Ehsun, you’re correct in saying the left side of the ‘=’ is assigned whatever is on the right. So you can almost think of it like an arrow “<=" (don't actually write that. That is an inequality statement Less Than or Equal To)

        In the second statement, you're assigning to the text property of the label whatever the "customText" has.

        The correct way to think about it is that the variable merely "points" to things. it doesn't actually store it.

        So when we write "NSString *customtext = self.textfield.text", we're saying, let's create a variable called customtext to point to whatever data is set at "self.textfield.text".

        Then in the next line, we're saying "let's set the label's text property to whatever customText is pointing to"

  42. Hey Chris

    I now understand the first video where we simply created the hello world label along with the hello again label. I’m not too far off mastering this one too.

    One part which is currently throwing me off: during this video at around 7:14, where you are creating the method for changing the text, you refer to the customTextField property, but then you say that it has a text property.

    So the property ‘customTextField’ itself has a property called Text?

    • Yup!

      Just like your ViewController is a class and it has properties, the UITextField is a class too and it has a Text property.

      We created the “customTextField” property to hold a reference to a UITextField object. (When you dragged a Text Field onto the storyboard, you were actually adding a UITextField object). So we create the “customTextField” property to refer to this UITextField object.

      When we need to do something with the text field object, we’ll go through our “customTextField” property to access it.

      If you’re confused about classes vs objects, give this guy a read: https://codewithchris.com/learn-programming/

  43. Hi Chris,

    I wanted to say a quick thank you for putting up these tutorials but unfortunately you’re already losing me. We went from not knowing how to code, to adding a simple text field, to an unstructured brief run down of so many different types of ‘data’ that I can’t even remember them, and in this video you’re just going far too fast.

    If you add a rest point in your video after each bit of entry it would allow new coders such as myself to check, absorb and understand.

    I’m trying to learn by keeping up with you but you’re whizzing round the screen and I have to keep pausing and going back to catch up. If I look at what you’re typing, I then go in to type it myself and bam, you’re a step ahead of me.

    I’m going to persist, but I learn better through listening and doing (I’m dyslexic so masses of text make me switch off).

    I like your style and your friendliness but this really isn’t a tutorial for someone who doesn’t know how to code. It’s a tutorial for someone who has done some coding but doesn’t know Xcode.

    I will get there!

    • Hey Chris,

      I agree partially with Matt here. I was going to make a comment to say that your tutorial videos are basically a little too fast. I’d just like to give you some constructive feedback.

      I do not think this video has an unstructured brief run down of many different types of data; quite the opposite actually. I think your video was structured well, but can easily leave people like me and Matt trailing behind as it moves on too quick. The content in the video is definitely understandable for a complete beginner. I took a few days to read and understand your articles on the basics of OOP, so this made me comfortable with all the terminology you use (class, variable, instance/object, property etc).

      However, as its my first time doing any programming what so ever, I think Matt nailed it when he said that if you allow small breaks after each input during the video for us beginners to take it in and understand what just happened, then your videos will be far easier to follow and understand. Everything else about your tutorial videos are great, just the speed at which new things are covered is a little too high.

      • Thanks for the constructive criticism! Really appreciate the feedback and the part about going too fast is something that I’ve heard from others as well regarding this Basics series. I edited the video too aggressively and it’s about time that I make some new ones on the basics so please give me a week or two to publish some new ones and I’ll factor in your feedback items! Thank you!

  44. Hello Chris, I’m loving the tutorial. I haven’t had trouble until I got to this section we’re it told me to run the app. Any help would be appreciated. I was wondering if you’ve seen this before

    Thanks

  45. Hi Chris! I am so glad for developers like you. Your tutorials help a LOT!. Thank you!
    Here is my problem. I’m running Xcode 4.2 and when I clicked the button to change the text. I get this message. Any input on how to fix it?

    • Hey Taco, you’re just missing a little bit here.
      In line 68, you want to write NSString *customText = self.customTextField.text;

      Notice the “.text” at the end? You want to assign the text property of the UITextField to the customText variable. The text property contains an NSString of what the user typed in. This is what you want to assign to your variable.

      Before, you were assigning the actual UITextField object to the customText variable.

      Hope that helps!

  46. Hey Chris! I like your tutorial. I’m very interested in game development, and do you plan to make tutorials about that?

      • I’m sorry, it’s my misspelling. They’re “self.HelloLabel.text” and “self.HelloLabel.Text”, I mean the difference between “text” and “Text”

          • Thanks Chris, but both works at my PC. I’m using XCode 5. Here is my code:
            – (void)viewDidLoad
            {
            [super viewDidLoad];
            self.lblHelloWorld.Text = @”test”;
            }

            Can you try it again with XCode 5, I don’t know if it works in XCode 4 or not.

            Thanks a lot.

  47. Hi Chris and thanks for the useful tutorial!

    Even though I have managed to follow the tutorial and get the expected results, there is something that I’m having a hard time understanding with my limited objective C knowledge. Basically what I do not understand is where does ‘- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event’ come from and where is it called. I understand what it does, it’s just that for me looks like a method declaration and I don’t see where it is used/called.

    I guess some things can’t be explained in a few lines and if this is the case maybe you can point me in the right direction with a link or something.

    Thanks,

    • Hey skamsie, great question!

      You’re right that it’s not specifically declare anywhere, nor do we explicitly call it anywhere.

      You’ll notice that in ViewController.h, on the @interface line, the “: UIViewController” indicates that ViewController is a subclass of the UIViewController class.

      By being a subclass of UIViewController, it also inherits all of it’s methods and properties. However, the touchesBegan method is not in UIViewController.

      UIViewController is a subclass of UIResponder which has the method.. so that’s where it really comes from. All we’re doing in ViewController.m, is “overriding” it.

      You can look at the UIKit hierarchy here: https://developer.apple.com/documentation/uikit

      And to find out about more about overriding, go here: https://codewithchris.com/how-to-make-iphone-apps-mvc-one-pattern-to-rule-them-all/ and scroll to the section about “What is Overriding?”

      • So part of the training here is to go through the notes as well and understand how the notes augment the videos. There is actually more information in the notes than in the videos, almost as though the videos are a starter course to the notes. Now the challenge is to go back and understand how I misunderstood the videos in the first place and that will throw even more light on why the code runs perfectly after everything in the notes have been applied. What you are really teaching us to do is to critique our own code and then learn how to hunt for more information across the web by asking the right questions.

  48. great tutorials. This worked great on initial view controller. But if you try to link buttons to actions on sub control views to actions it wont let you link???????

    • Hey Dwayner, thanks for reading and following along! Can you give me an example of what you mean? Maybe a screenshot or something? You can contact me via the contact link at the top of the site!

  49. Hi,
    In XCode 5 when I was dragging the label over to the viewcontroller.h source code, the property registration window default suggested a weak connection instead of a strong one. Is it important to change it to a strong connection?
    What is the rule here when defining the property?

    Frank

  50. Hey Chris.

    Thanks for god tutorials.

    I have a problem when i run my simulator after I implemented the changeTextField.

    Whenever I click the button an error comes. It is thread1: signal SIGABRT and in the console this text is printed: “libc++abi.dylib: terminating with uncaught exception of type NSException”

    Can you please help me πŸ™‚

    • Hey Simon, thanks for following the tutorial! Unfortunately the error doesn’t give me anymore clues. Can you check this for me: In your storyboard board, right click the button to see the connections and see what action methods your button click event is attached to. Then in your .m file, make sure that those action methods exist and pay attention to any typos as well! If you find that it’s connected to a method that has been renamed or doesn’t exist, just click the “x” beside the connection to break it.

      If you’re still seeing the problem after that, please get into contact with the link at the top of the site and we’ll get it figured out! Thanks

  51. hey Chris,

    first of all thanks for sharing your knowledge with us. I am glad to found these videos on Internet cuz I have been thinking to start coding some IOS app but I didn`t know where to start. I hope this will get me going on.

    I have problem launching my app. I fallowed all the step with you but when I hit the run button. it says building successful! thn takes some time to open up but never opens.

  52. Hey Chris, I’m having trouble with removing the keyboard. I put the [self.customTextField resignFirstResponder]; under the handleButtonClick but whenever I run the simulator and I click the button, I get an error message, terminating app due to uncaught exception … unrecognized selector sent to instance 0x8e38400. I’m not sure what it means, I’ve got all three fields defined in the header file.

  53. Hey Chris! I’ve been hitting my head up against the wall trying to figure out some iOS concepts, and your tutorial was where things finally started to click. Thanks for writing it πŸ™‚

  54. Hey Chris, tutorial is so awesome!! But I have a problem working in my macbook. It seems I cannot drag the UI elements into the viewcontroller.h file like you did in the video. I use xcode 5. any ideas? thanks!

  55. Hey Chris, awesome tutorials!
    I’m having lots of issues with my xcode5 for some reason. When trying to drag into my viewcontroller.h I keep getting the error “Could not find any information for the class named ViewController” and I’ve tried every type of fix the internet tells me to but still doesn’t work. Despite this I tried to just do the code itself and link my labels and buttons after writing it out and I can link them, but then when making the methods in my .m file I get a build that works but clicking the button does nothing. Any suggestions? :S

    • Hey Tyler, so the method in the .m file looks something like this right?
      – (IBAction)clickMethod
      {
      NSLog(@”method fired”);
      }

      Can you put the nslog statement like i have in the method? Then run your app and click the button and check the console area to see if you see “Method fired”. The console window is the window pane at the bottom of the xcode interface.

      • I put the NSLog in and I don’t get anything in the console besides this error:

        “UserInteractionDemo[2842] : CGContextSetFillColorWithColor: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.”

        Which is really weird. I realize now that the IBAction method isn’t linked to the UIButton because I got the same error as I did in the viewcontroller.h method when trying to control and drag into the .m. I manually put in the code but now I can’t link it to anything, it simply won’t let me!

        • Hey Tyler! You’re getting somewhere! That error is actually unrelated to the IBAction not getting fired.

          So now it’s obvious why it’s not working πŸ™‚ Because the IBAction method is not hooked up to the button event! So all you need to do is to grab the circle to the right of the “Touch Up Inside” event and drag it over the the view controller icon below your storyboard view, and then when you let go of your mouse, it will popup a window and you can select the “handleButtonClick” IBAction.

          After you do this, clicking the button should call that method.

          As for the error in the console, i think that may just be an xcode bug. I see that you changed the color of your button text. If you changed the color through Interface Builder, you’re not doing anything wrong.

  56. Hi Chris, I have been going through this tutorial and I am a little confused as why my code works without the use of the self keyword!

  57. Chris! Great tutorial! I noticed that for your button connection you use IBOutlet and it worked fine in the demo, but shouldn’t the connection for a button be IBAction? just trying to get this clear in my head.

  58. Hey Chris,

    Your tutorials are really great, I’m going through them and trying to completely understand everything before moving on.

    I noticed that some of the code that you have us input is in brackets [ ] while some isn’t. For example:

    self.customlabel.text = self.customTextField.text;
    [self.customTextField resignFirstResponder];

    It wont work properly if I remove the brackets. Why is that? When are brackets needed, and when are they not?

    Also, I noticed that many times the first letter in a string won’t be capitalised, but following words will be, like in “resignFirstResponder” above. Is there any reason for that?

    Really great tutorials, thanks again for making them!

  59. I get as far as adding the properties but when I add the button handler and hit “play” to invoke the simulator, the simulator screen is black and it looks like there is some kind of threading error and/or an NSException. Help!

    • Hey Malcolm, one common error that’ve noticed happen a few times is some people will add the properties, and then delete them and redo it to add separate properties. What happens then is now the element in the storyboard is connected to two properties, one of which doesn’t exist.
      Can you right click on each of your elements in the storyboard to look at the connections and make sure that any property it is connected to actually exists in the .h file?
      If it still fails, let me know and I’ll send you an email to take a look at your xcode project!

      Thanks

  60. Hi Chris. I have followed your instructions, but ended up getting the error message after a text is put in to the text field and the button is clicked: libc++abi.dylib: terminating with uncaught exception of type NSException.
    Do you know what this might be?
    Thanks so much!

    • Hey Giedrius, it may be because the button is hooked up two handlers (one doesn’t exist). Can you right click on the button in the Storyboard and check that the click event is only attached to a method that exists in your .m file? If you see the click event is connected to a method that you deleted already, also delete that connection. Let me know if that works!

  61. Hi Chris. I believe I have followed your instructions, but I’m met with an error which says “UserInteractionDemo[60130:a0b] *** Terminating app due to uncaught exception ‘NSUnknownKeyException’, reason: ‘[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key changeTextClick.'”

    Any ideas where I went wrong?

    • Hello!

      I’m going to need to see a little more code. I’ll email you for the xcode project and see what’s going on. Thanks!

  62. Hello Chris ,
    Thanx for the tutorials , they r very easy to follow.

    I am getting the below error …
    return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));

    Please help me , im not able to proceed after this.
    Rgds
    Shaan

    • Thanks for asking! I’ve got your email and xcode project. I’ll be taking a look at it today to see what the issue is. Thanks!

  63. I have attempted to follow through but I am getting the following error reported in Debug area:
    2013-10-16 21:38:49.067 UserInteractionSven[1629:a0b] *** Terminating app due to uncaught exception ‘NSUnknownKeyException’, reason: ‘[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key handleButtonClick.’
    What’s wrong?

  64. I have a book written in word which consists different language sets(Turkish and Arabic)[left to right\right to left]. I want to write e-book application. Is there a framework or some template codes for that. Or Should i just use standard components..
    App should has search capability.

    Thank you for your videos.

  65. I am getting an error message on the code : self.helloLabel.text = @”default text”; error says: Property “text” not found on object of type ‘UIView*’. The word “text” was not coming up as an auto option and both helloLabel and text are in black, not color print. Thanks!

    Went back and double checked prior steps.

    • Hey Frank, it looks like the self.helloLabel property is not set to pointing to the UILabel.
      Go into ViewController.h, delete all your properties.
      Then go into your Storyboard, right the UILabel to bring up a menu showing what properties its connected to.
      Then click the little ‘x’ beside the connection to break it.
      Then repeat this for the other UI Elements (The UITextField, the UIButton).

      After you’ve reset everything, click the UILabel in the Storyboard, then hold CTRL and drag it over to ViewController.h. Name it “helloLabel” and now go to ViewController.m and try typing the code “self.helloLabel.text” and see if “text” is coming up as an auto option. This will be your clue that the property is referring to the UILabel correctly.

  66. Hello Chris,

    I am paying extreme close attention to detail and I have noticed that the “HelloLabel” has differences. Sometimes the “H” is capitalized and sometimes the “h” is not capitalized. Does that matter in this instance?

    Thanks,

    • Hey thjames2, good eye! they should all be consistent. If i named it “helloLabel” with a lowercase then subsequently i need to use the same capitalization when referring to it again.
      Thanks for the heads up. I’m going back and correcting this typo!

  67. Hi Chris, I have started to use your exercises as a means to learn how to use xcode and develop apps for the iPhone/iPad. my primary interest is to build a commercial application that can integrate in to MS SQL. I need to be capable of executing SP’s and returning data from a view or likewise. do you have guidance on this in later exercises? if not, are you able to guide me to resource similar to this?
    I appreciate your time and dedication to teaching the masses. Thank you on behalf of us all πŸ™‚

    • Hello Phillip!

      I probably won’t be covering something as advanced as that for a while to come.

      The iPhone/iPad app is just a client, so on a Windows server you have to create a ASP.NET web application that connects to the MSSQL database. The web app will be responsible for all of the data management (reading and writing data, executing stored procs).

      The web app will also expose a rest based API and implement some sort of authentication so that it’s not open to the public.
      The API will include methods that cause the web app to perform various data management tasks.

      Then from the iPhone/iPad client apps, you can write code to authenticate with the API and call the methods of the API, pass it data etc..

      The iOS app will not be able to directly access the MSSQL server unfortunately.

      Hope that helps!
      Chris

  68. hi i’m having a bit of trouble when i run i get this,
    return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    any thoughts?

    • Hello amathias1, unfortunately i’m going to need to see more of the code. Based on the error, i’m guessing it’s a simple typo. I’ve sent you a separate email; can you send me your project and i’ll point out the error for you? Thanks!

    • Hi Chris,

      I’m getting the exact same error as amathias1.
      Could you please send me an email so I can reply with my projectas I’ve not had any success finding a typo.

    • Hi Guys,

      I found that I got this error when I accidentally ctrl+click dragged the view element into the header file instead of ctrl+click dragging the label.

      So instead of having this in the ViewController.h:

      @property (strong, nonatomic) IBOutlet UILabel *helloLabel;

      I had this, which caused the error:

      @property (strong, nonatomic) IBOutlet UIView *helloLabel;

      You might have accidentally dragged the wrong thing into the header file. As a complete noob, I might be wrong but this is what it was for me πŸ™‚

  69. Could you please explain what the different parts of coding mean from this part? I just think it would allow my abilities grow, I am new to coding so please don’t use too many words I don’t understand. Thanks for the Tutorials they are helping me learn.

    Thanks

    • Hey Dimmie, Take a look at the following lesson after the practice.. i usually do practice and then recap of the practice to go through in more detail what everything means.
      Thanks for reading!

  70. Hay Chris I just wanted to ask if there is a way to do a couple of things with this, first take whats entered into 2 text fields (Numbers) and do a sum (A/B=C) and secondly display them in a popup box.

  71. Want to know more on the method you have written, please slow down and explain, i am a newbie.

    – (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.customTextField resignFirstResponder];
    }

    • Hello ranajit,

      The touchesBegan method is a way to handle user touches on the screen. You can read a bit more about it here: (http://bit.ly/1awzeqU)

      But essentially when the user touches the screen, that method is triggered and the code in there:
      “[self.customTextField resignFirstResponder];” makes the on-screen keyboard go away, otherwise when you tap out of the text field, the keyboard won’t disappear.

      “self.customTextField” is referring to the textfield and “resignFirstResponder” is a method of the textfield that minimizes the on-screen keyboard.

      Hope that helps!

  72. Hi Chris, i just wanna ask is there any kind of tutorial about how to make GridView in Xcode ?? or perhaps you can refer me to any web pages that related to my question. Thanks in advance..

    Cheers

Leave a Comment

27 Shares
Share
Tweet
Pin
Share
Buffer