Build your first iPhone app [Code Tutorial]

topimage_hellotipBuilding iPhone apps is something that almost everyone wants to be able to do these days. Something that is traditionally the “first” app that you write when learning a new programming language is known by many as a “Hello World!” application, or something along those lines. Well, if you are looking to get a start in programming for iOS, or have no experience in Objective-C and want to get a quick look at the language, this tutorial is for you. This only requires you have the following prerequisites:

- A Mac (sorry, Windows users!)
- An Apple ID to access the Mac App Store

If you fit those, get on your Mac, open the Mac App Store, search for Xcode and install it. It is free, so don’t worry about having to buy something! In this tutorial, we are taking the basic idea of a “Hello World!” application and adding a few things to it. Instead of just making text appear that says “Hello World!”, we are going to actually make it where a user can input their name into a text field, then when a button is pressed it will show a popup telling that user hello. Let’s get started…

Create ProjectFirst thing’s first, you want to create a new project upon opening Xcode. I chose a “Single View Application” (seen on the screen before the one posted above), and named the project HelloTiP. Of course, you can name it whatever you wish to name it. Organization name is exactly what you’d think, your organization name. For company identifier, it usually is in the form of a backwards URL; for example, “com.todaysiphone”. The product name is attached to the end of the company identifier in order to get the bundle identifier, which in this case is com.todaysiphone.HelloTiP. Class prefix is what you want to be in front of the file names. Personally, I tend to use a two letter contraction of the product name, hence HT. Afterwards choose your device the app will run on, you can choose iPhone, iPad, or Universal (both iPhone and iPad). For this tutorial, I am just going to use the iPhone (however iPad steps are near identical).

StoryBoard_ButtonThe first file we are going to edit is our Main.storyboard, found on the left in your projects folder. We need to add a Button, so in the bottom right where you have your interface objects, find Button (or you can use the search at the bottom to find it) and drag it onto your view (yes, it’s as easy as drag and drop). Make sure you just put a Button and don’t try to put a Bar Button Item onto your view wherever you want. You can rename it whatever you want by double clicking on it; I called mine “Press This!”

StoryBoard_TextFieldNext we need to add a Text Field to the view so that our user can type in their name. Do the same thing as the Button and find a Text Field int he objects menu on the side and drag and drop the text field onto your view, placing it wherever you want just as before. To me it seemed more natural to have the Text Field above the Button, as the symbolize that we want to have the user time the name before pressing the Button. If you want to add some placeholder text so that the user knows what they should be typing into the field, open the Attributes inspector on the right side of the screen, and type what you want it to say in the “Placeholder:” section. I put “Type your name here…”. Placeholder text is removed once the user has begun typing in the Text Field.

Now on to the fun part, code! As you’ll see, I’ve put comments in the code with numbers (the vibrant green color text), so below each image will be those comments and then the corresponding explanation for each part. If your Xcode syntax highlighting (how the code is colored) is different than mine because you are still on default, fret not, I just prefer this theme, and it has no effect on the code. For those interested, you can change the theme by going to Xcode > Preferences > Fonts & Colors. Mine is set on “Dusk”.

headerTo get started, open up your view controller header file. If you followed my naming scheme, that’ll be HTViewController.h.

/******** 1 ********/
Most of this part is already written for you, and all you need to add is the <UITextFieldDelegate> at the end. We will use this later when dealing with our Text Field.

/******** 2 ********/
Add this line so that we can connect our Text Field in our Main.storyboard file. IBOutlet stands for Interface Builder Outlet, which means that we can connect it inside of Interface Builder (which is what you see when editing the Main.storyboard file). UITextField is the programmatic name of a Text Field object, and textField is the name of our Text Field to be used in our code.

/******** 3 ********/
This line represents our action of pressing the Button we added. IBAction, just as IBOutlet, is short for Interface Builder Action. IBActions are fired when a certain UI element is triggered. You can connect this to things other than Buttons, but obviously ours is going to be assigned for when a user presses our Button. The “pressButton” name is arbitrary, and can be whatever you want.

Connect_ButtonNow, going back over to our Main.storyboard file, we can connect both our IBOutlet and our IBAction. On the left side, open up the Connections inspector so that we can connect them. Drag from the dot next to pressButton: over to our Button that I named “Press This!” and you will get a small menu of options on release, choose “Touch Up Inside”. Connect_TextField

Next, find the “textField” outlet under Outlets, and drag that to our Text Field. Now we are done connecting everything in Interface Builder and we can add the functionality to our app!

pressButton

Assuming you chose the same naming convention as I did, open up your HTViewController.m file. The .m, or implementation file, is where the bulk of your code goes. Here you implement actions and other various functions and methods in order to give functionality to your app.

Note: I forgot to show in the code that you must synthesize textField. Do this by adding the line “@synthesize textField;” (without quotes) under the line “@implementation HTViewController” at the top of HTViewController.m as seen on the highlighted line here: textField.

/******** 1 ********/
For starters, we are going to implement our IBAction of pressButton. To do this, you can simply copy/paste our action from HTViewController.h, except instead of a semi-colon at the end you are going to put an opening bracket and a closing bracket. Once you type the opening bracket and press enter, Xcode will automatically create the closing bracket for you and indent your cursor properly.

/******** 2 ********/
Next we are going to declare an NSString that we will assign the text the user types into the Text Field to. As you can see, I name the string textFieldText so that I know what it is, and I put textField.text to say that I want the text from the textField.

/******** 3 ********/
We now declare a new NSString that we are going to use as the message for our popup. This string is called alertMessage so I know what I am using it for, and is equal to a string with the format “Hello, %@!”. The %@ will be replaced with whatever information I pass to the string, which in this case is our textFieldText string. This way, it will have Hello then our user’s inputted text.

/******** 4 ********/
Now we create our UIAlertView (the thing that you always see popping up in iOS). I name the UIAlertView “alertView for simplicity’s sake, and pass the title “Hello!”, for the message I pass our alertMessage string we just created, set the delegate to nil (we don’t need one here), our cancel button title is “Nice to meet you.”, and we have no other buttons so we pass nil to otherButtonTitles. This creates the UIAlertView that you see on the iPhone screen at the very top of this post.

/******** 5 ********/
Next, we have to actually show our alert. To do so, you simply type the name of our alert (alertView) and type show to show it. Simple enough, right?

There is a problem now, however. If you run the app and have the UI set up just as mine is, you’ll notice that there is no way to actually hide the keyboard after you are done typing, which is a problem because our Button is under the keyboard. So, let’s make a way to hide the keyboard.

viewDidLoad

/******** 1 ********/
In the viewDidLoad function at the top of HTViewController.m, we need to set our Text Field’s delegate as the current ViewController. To do that, simply type “self.textField.delegate = self;” as seen above. This is why we put <UITextFieldDelegate> in our HTViewController.h file earlier.

dismissKeyboard

/******** 1 ********/
After that, we need to create two more methods that will handle dismissing our keyboard. The first one will allow the user to tap somewhere in the view to dismiss the keyboard. Still inside HTViewController.m, add “-(void)touchesBegan(NSSet *)touches withEvent:(UIEvent *)event” and in between your brackets type “[self.view endEditing:YES];”. Now if you run the app, you can tap anywhere above the keyboard (except in the Text Field of course) and it should hide the keyboard.

/******** 2 ********/
What if your user naturally presses the return key in order to hide the keyboard instead? Well, that’s what the next method does. Below the previous (or almost anywhere you want, really), type “-(BOOL)textFieldShouldReturn:(UITextField *)aTextField” and in between the brackets type “[aTextField resignFirstResponder];” and “return NO;”. This tells the keyboard for the Text Field that when you press return, it should hide the keyboard. Now when you run the app, you can tap anywhere above the keyboard or press return in order to hide it.

After this, you’re all set! Run the app, type in your name, press the button, and you should be presented with an alert view with our string that we created. If something isn’t quite working, you can head on over to the open source page for this project on GitHub here: HelloTiP. All the comments are in the code, so you can follow along from there instead of my screenshots.

What other tutorials would you like to see? Are you a beginner programmer looking to learn iOS? Let me know in the comments, and tweet tutorial suggestions to @TiP_Kyle. I look forward to seeing them!

 

 

 

 

 

 

 

Tags: , , , , , ,

  • http://www.joshspadd.com/ Josh Hrach

    Simple tutorial. Very easy to understand. Great article.

    Do you do a lot of programming, Kyle?

    • Kyle Frost

      I do! I’m currently a Computer Science major, so programming is my game. Glad you liked the tutorial. Are there any thing’s related you’d like to see?

      • http://www.joshspadd.com/ Josh Hrach

        Not that I can think of offhand. I’ve got a general grasp of iOS/Objective-C at this point. Only thing I can think of is what I mentioned in the other post. I’m used to working with MySQL on the web (and off) and that’s probably the thing I have yet to figure out with iOS.

  • Anthony Snyder

    My view looks similar to that. I’m not seeing textField under outlets…