Subscribe ( RSS )

iPhone Programming Tutorials

Got It!
Intimate Secrets
Dynamic photo effector
Where To Eat? Find restaurants using GPS.
GPS Where To Go? Find Points of Interest using GPS.
Advertise You App Here

iPhone Programming Tutorial - Creating a ToDo List Using SQLite Part 3

This is part 3 in our multipart series of creating a todo list for the iPhone.  For this, you must have completed the following tutorials.

The focus of this tutorial will mainly be on viewing the todo items when selected.  I will also show you how to update the todo status.  This will require us to use interface builder.  When you are completed, you will be able to edit todos through an interface similar to this:

Bringing Your Code Up To Speed

For this tutorial, we will need to get the last variable from the todo database.  This is of course being the status variable.  If you recall, it’s a boolean value (1 for complete, 0 for in progress).  We need to get it from the database and associate it with the todo object.  First let’s create a property to hold this value.  Open todo.h and add the following code:

So a few changes here…First there is the added NSInteger status.  This will be the property we associate with the status (complete or not) of the todo.  We also create a property from it.  Next, there is a BOOL property called “dirty”.  We will use this object to signify when a todo has been altered.  You will see how this comes into play when we implement the dehydrate method. Also, I have added 3 method signatures.  updateStatus will be the method called when we want to update our status variable.  Similarly, the updatePriority method will be called to update the priority.  Finally, we have added a dehydrate method.  This method should be familiar (or confusing) if you have messed with Apple’s books example.  Basically, it will be used to save the state of the todo to the database.  We will be calling this method on each todo item when the program exits.  I will show you how to do this in a little bit.

Be sure to add the status variable to the synthesize line.  Also, as we did before, we need to create a static sqlite3_stmt to hold the compiled dehydration statement.  Add the following code to Todo.m:

Now let’s implement the methods.  Add the following code:

The first two methods (udpateStatus and updatePriority) are pretty strait forward.  They update the status and the priority of the todo and then set the “dirty” property to 1.  This signifies that the todo has been altered and will need to be saved to the database.

Finally, there is the dehydrate method… We will call this method on each todo upon termination of the program.  If the todo is “dirty” meaning the dirty property was set to YES, we will need to save the new data to the database.  The database code should look pretty similar to code in previous tutorials.  First, we check to see if the dehydrate_statement is equal to nil.  If you recall, this will only happen the first time this method gets called.  Next we create the update statement and then bind our variables to each of the “?”’s.  Notice the ordering.  The numbers represent the question marks from left to right (1 being the first, 2 being the second, 3 being the third).  It took me quite some time to figure this out.  Finally, we execute the sqlite statement by calling sqlite3_step and then reset the statement.

The last thing we need to do to Todo.m is change the SELECT statement in the initWithPrimaryKey method to grab the ‘complete’ field.  Update the code to look like the screenshot below:

There are not really many changes.  The first change is the added status to the synthesize line.  Next, the sql statement was updated to read

SELECT text,priority,complete FROM todo WHERE pk=?

This allows us to get the “complete” field from the database.  Finally, there is the line “self.status = sqlite3_column_in(init_statement,2);”.  This is assigning the status property to the data at index 2 in the sql data array.  We can now use this field.

One thing we need to do for the navigation to function properly is add a title to our main view.  Open up rootViewController.m and add the following code to the viewDidLoad method:

Create the Todo Detail View

Now we are going to create the view that will display when the user selects the todo in the UITableView.  Go ahead and open up Interface Builder by selecting one of you existing nib (.xib) files.  Once it’s open add a new View by clicking File -> New and select View. Drag the following controls.

  • UITextView
  • UISegmentedControl - For this you will need to set the number of segments to 3.  You will also see a dropdown menu below this option.  Select each segment and fill in one of the priorities for the title.  Here is a screenshot. You should give a title to each (Low , Medium, High).

  • UILabel - This will be used to display the status
  • UIButton - Users will click this button to update the status (Mark as complete)

When you are done, your interface should look something like this (but probably better):

I know that my interface doesn’t look the coolest.  I’m a programmer not a graphic designer… Ok save this view by pressing Command-S.  Make sure you are in your current projects directory.  Name it TodoViewController and press Save.

It will then ask you if you want to add it to your project. Check the box next to the word todo and click Add.

Now close Interface Builder.  Next, we are going to add the viewController class and set up variables to interface with this view.

Create TodoViewController Class Files

Click File -> New File… Select UIViewController Subclass and click Next.

Name the file TodoViewController and make sure that the box that says “Also create TodoViewController.h” is checked and click Finish.

Open up TodoViewController.h and add the following code.

Basically, we are setting up Interface Builder Outlets for each of the UI components to be connected to.  Notice, the UIButton has an IBOutlet.  This is because we will need to update the text on the button depending on whether or not the todo is completed.  Also, I have an IBAction called updateStatus.  We will be connecting this to the button we created.  It will toggle the status (pending/complete) of a todo item.  Finally, we see the updatePriority method.  This method will be called when the user selects one of the priority segments in the UISegmentedControl. Next, open up TodoViewController.m and add the following synthesize code:

This will allow us to get and set these variables.

Before we connect this code to the Interface, we need to implement the methods that will be called when the user presses the button to mark a todo as complete as well as when the user presses a segment in the UISegmentedControl.  Inside of TodoViewController add the following methods.

Let’s go through this.  First we see the updateStatus method.  This gets called when a user presses the button to alter the status.  We basically check the current status of the todo (whether or not it’s completed) and depending on that, change the text to be displayed on the UIButton.  So, if the todo is not complete (in progress) and this button is pressed, the text will be changed from “Mark As Complete” to “Mark As In Progress”.  Finally, we call the updateStatus of the todo and pass the new value (1 or 0) to it.

Next we see the updatePriority method.  It simply reads the value of the UISegmentedControl by calling the selectedSegmentIndex method on it.  The next part looks a little messy.   There are 2 reasons that reason we can’t just pass the value of the UISegmentedControl directly to the method.  The first is, the UISegmentedControl is ordered in acending order (1, 2, 3…), but our priorities are in descending order (3 = low, 2 = medium, 1 = high).  This is where the “2 - priority” comes from.  Next, UISegmented controls are “0 indexed” meaning the indices start at 0 and increment from there.  So we need to add a “+1″ to the index as our todo priorities start at 1.

Now we need to connect the UI Components in Interface Builder to this code.  Double click on TodoViewController.xib to open it in Interface Builder.

Connecting UI Components To Code

We first need to associate this view with the class we just created.  In the Interface Builder, click on the File’s Owner object.  Next click Tools -> Identity Inspector.  You should see a drop-down next to class.  Select TodoViewController from this list and you will see the variables we just created appear in the boxes below.

This is what the Identity window should look like after you have selected TodoViewController.

Now that the class is associated, we can begin connecting the components.  We will start by connecting the view.  Click on the top of your view window to select the view itself (make sure you haven’t selected any of the UI components).  Click Tools -> Connections Inspector.  Next to where is says “New Referencing Outlet” click in the circle and drag it to the “File’s Owner” object and release it.  The word “view” should pop up.  Click on the word view.  It should now look like this.

Now repeat these steps for each of the components (UITextView, UISegmentedControl, UILabel, UIButton) connecting each to the “File’s Owner Object”.   Instead of the word “view” popping up, you should see the variable name for the corresponding variable that you want to connect the component to.   So for the UITextView, you should see the word “todoText” appear when you drag it to the File’s Owner object.

We need to connect the UIButton to the updateStatus method we created.  To do this click inside the “Touch up inside” circle and drag it to the “File’s Owner” object.  You should see the text “updateStatus” appear.  Click on it.  If all goes well it should look like this.

The last thing we need to do inside of Interface Builder is connect the UISegmentedControl.  Click on it in your view and then click Tools -> Connections Inspector… Click on the circle next to the “Value Changed” method and drag it to the “File’s Owner” object.  You will see the method updatePriority popup.  Go ahead and click on it.  Your window for the UISegmentedControl should now look like this:

Now, let’s display this view when a row is selected.  Close Interface Builder and open up RootViewController.h and add the following code:

We need a variable to associate with the TodoViewController that we will be transitioning to.  Next, open up RootViewController.m and add the following code to synthesize this property.

Keeping the UITableView Up To Date

Whenever a todo item is altered (status or priority) the UITableView needs to be updated with the new changes.  Add the following code to the viewWillAppear.

The line [self.tableView reloadData] reloads the table data every time the view appears (or reappears).  This will ensure that our table is always up to date.

Now add the following code to the didSelectRowAtIndex method:

This is quite a bulky method with a lot of familiar code.  First, we get a handle to the appDelegate and the todo object that was selected.  Next, we push the todoView (the view you created in interface builder) on to the viewController stack to transition to it.  After that, we are setting some of the properties of the view.  The title is set to the text of the todo (it will get truncated if it is too long) and the UITextView is also set to the todo text.  Next, we are translating our priority to an index for the UISegmentedView.  I explained why this was necessary above.  Then the index of the UISegmentedControl is set by using the setSelectedSegmentIndex method.  Finally, we set the text of the button and label based on the status of the todo.

The very last thing we need to do is tell the application to save itself when it closes.  Open up todoAppDelegate.m and add the following code to the applicationWillTerminate method:

If you ask me, this is some freakin sweet functionality.  The method “makeObjectsPerformSelector” is a built in method on an NSArray.  It basically loops over every object in the array, calling the method you pass in to it on each one.  It’s like doing a for loop and calling the todo[x].dehydrate method for each todo.  Only this is much cleaner.  So, to reiterate, this method will call the dehydrate method on each todo.  If the todo is “dirty” meaning it was altered, it will be saved to the database, otherwise the dehydrate method will do nothing.

* One thing to note.  The applicationWillTerminate method will not be called if you quit the simulator while the application is running.  To make sure it gets called (and the todo data gets saved) make sure you press the home button on the simulator after you make alterations to the todos.  If you simply press Apple-q and quit the simulator while inside of the todo program, no data will be saved and you will post angry comments on my site telling me that my tutorial is wrong.

Click Build and Go and just sit back and enjoy the magic of rock! I mean XCode…

When you select a todo item, your screen should look something like this:

Well, that concludes part 3 of our series.  Join me next time, when I will show you how to add and delete todos from the SQLite database. If you have any comments or questions, feel free to leave them in the comments section.  I would love to hear them.  Please subscribe to the RSS feed if you want to be automatically notified of new tutorials.  If you get lost at any point, you can download the sample code for this tutorial here.

Happy iCoding!

iPhone Programming Tutorial - Populating UITableView With An NSArray

The goal of this tutorial is to show you how to populate a UITableView with data from an array of objects. This will be the building block to display XML data as well as SQL data.

The theme of this application will be fruit. We will create an array of “fruit” objects that have some additional information besides the name. We will populate a UITableView with the names of the fruits. When the user selects a fruit from the list, the view will transition to another one and display specific details about that fruit.

I will try to be as detailed as possible however it would be useful if you have completed the following tutorials as I will use concepts from each of them:

In this tutorial you will learn:

Open up X-Code and Select File->New Project… Select Navigation-Based Application and click Choose…
Name your project Fruit.

We are going to create our “fruit” objects that will be used in the application. If you are not too familiar with object oriented programming…Google it. That tutorial would be a little too huge for me to write.

Click on File -> New File… The object we are creating will inherit from NSObject, so select NSObject Subclass and click Next.

The next screen will ask you to name it. Go ahead and name it “Fruit” and make sure that “Also create Fruit.h” is checked. It should look like the screen below. Then, click Finish.

Now, we are going to define the properties of a “Fruit” object. For this application a fruit will have a name and a description. Open Fruit.h and add the following code:

We have created the properties needed to represent our fruit. There is one line that you may be unfamiliar with. The line -(id)initWithName:(NSString*)n description:(NSString *)desc; is a definition for a function. This function will be called to initialize a Fruit object. All NSObjects have an init method, but we want to create our own so that we can pass in a name and description when the object is created.

Open up Fruit.m and add the following code:

Here we implement the initWithName method. The code here seems pretty straight forward. We are basically setting our local copies of name and description to the arguments passed to this method. The important thing to notice here is the return self line. This is crucial for using this method as a constructor. It allows this function to return the newly created instance of a fruit object.

Next, we are going to set the title of our main view. This is necessary to create a back button when transitioning between views. Open up RootViewController.m…In the viewDidLoad method, add the following code:
We are setting the title property of the RootViewController object to the string “Fruits”. Also, be sure to add the #import “Fruit.h” line at the top to include the fruit object in our project as well as @synthesize fruitView to add the “getter” and “setter” methods.

Next, we are going to create an array of fruit objects. Open up FruitAppDelegate.h and add the following code:

All we are really adding here is an NSMutableArray property. I used NSMutableArray instead of NSArray because it has a few more methods making it more flexible.

Now, open up FruitAppDelegate.m and add @synthesize fruits to the top. This is so other objects will have access to the fruits array. Also, be sure to include the import statement for Fruit.h.

Now add the following code to the applicationDidFinishLaunching method.

What we are doing here in the 1st three lines is creating new instances of a fruit object. Notice that instead of calling init, we are calling the initWithName method that we created. This is allowing us to pass in a name and a description to each of the fruits.

The next line [self.fruits = [[NSMutableArray alloc] initWithObjects:apple,orange,watermelon,nil]; builds a new array from the objects we just created. It is important to pass in nil as the last argument in an NSMutableArray. It will not work unless you remember this.

Now we are going to create the view that will be displayed when the user selects a fruit. Double click on any one of your .xib files to open up Interface Builder.

Click File -> New and select view and click choose.

You should now see the new view (it will be blank) and the objects associated with it. We need some sort of text field to display the description of the fruit. For this tutorial I have chosen a UITextView as opposed to a UITextField. This is because a UITextView is multi-line and is great for displaying more than one line of text. So, go ahead and drag it on to your view. Your view window should now look like this:

Now click File -> Save. One important thing to keep in mind is to make sure you are saving it in the current project’s directory. It seems that every time I add a view to a project, the default directory is not my project’s directory. Name this file FruitViewController and click Save.

Another window should show up after you click save. It is asking you if you want to add this view to your project. Just check the box net to Fruit ,click Add, and close Interface Builder.

Close Interface Builder and go back to X-Code.

We need to create a ViewController to handle our View. Click File -> New File… Select UIViewController subclass and click Next.

Name this file FruitViewController.m and check the box that says “Also create “FruitViewController.h” . Click Finish.

Now we will declare an Interface Builder Outlet for the UITextView that we added to the view. Open up FruitViewController.h and add the following code.

This line allows us to associate the fruitDescription property with the UITextView we created. Open up FruitViewController.m and add this code underneath @implementation keyword. This creates default “getter” and “setter” methods for the fruitDescription property.

Double click on FruitViewController.xib to open it in interface builder. We need to connect the view to the FruitViewController class we just created. Click on the File’s Owner object.

Click Tools -> Identity Inspector. Select FruitViewController from the dropdown next to class. Notice that under the Class Outlets section you will see the UITextView property we created.

The last step in interface builder is to connect the UITextView. Click Tools -> Connection Inspector. You should see an Outlet that says fruitDescription. Click in the corresponding circle and drag it over the UITextView on your view and release it.

Now, click the circle next the word View under outlets and drag it to the View object inside of the window that says FruitViewController in the title. When you are done the screen should look like this:

Now close Interface Builder.

The first thing we are going to do here is create a property for our new view so that it can be transitioned to when a fruit gets clicked on. Open RootViewController.h and add the following code:

We are just creating a property for the fruitViewController that we added to the project. Also note that I added the #import “FruitViewController.h” line. this will allow us to create new instances of the FruitViewController object.

Now open the RootViewController.m and find the numberOfRowsInSection method. This method tells the UITableView how many rows it will be displaying. In our case it will be the size of the array of fruits. Add the following code (click the image to enlarge):

The first line allows us to gain access to the appDelegate of our application. This is where we defined the fruit array. Once we have access to the delegate the count property of the fruit gets returned.

Now find the cellForRowAtIndexPath method and add the following code:

So the first line we added is the “FruitAppDelegate *appDelegate…” line. Again, this is giving us access to the appDelegate object where we declared the fruit array. The next line calls the objectAtIndex method on the Array of fruits. The index we will be using can be accessed via indexPath.row. This is an integer value representing each row of the UITableView. Finally, we call the setText method of the cell, to display the name of the fruit in each cell at the given index.

 

This is the last step. We are going to detect which row in the UITableView the user selected. Find the method called didSelectRow and add the following code(click image to enlarge).

This method gets called every time a user taps on a cell in the UITableView. The parameter indexPath has a property called row that is the integer value of the cell the user clicked on. To access this, we call indexPath.row.

The first line again gives us access to the appDelegate. The next line indexes into the fruits array and makes a copy of the selected fruit object.

The next section starting with “if(self.fruitView == nil)”, initializes the viewController if it hasn’t already been initialized (see my previous tutorial if you need more of an explanation on this). One thing to take note of: Make sure that the parameter you pass to initWithNibName matches the name of the .xib file you used for your view. So in our case, its FruitViewController.

Following this line is the line that pushes the viewController on to the navigationController stack. This causes the view to transition to the new view.

The last 2 lines pass the fruit information to the new view. They are fairly self explanitory. We first set the title of the view to the name of the fruit and then set the description text to the description of the fruit.

Now click Build and Go and your app should launch. Here are some screenshots of how it should look.

And after clicking on a fruit…

Well, I hope that you got a lot out of this tutorial. As always, if you have any questions or comments, feel free to leave them in the comments section of this post. We also have a forum to help you will all of you iphone related questions. If you get lost, you can download the sample code here

Happy iCoding!

iPhone Programming Tutorial - Transitioning Between Views

This tutorial will focus on transitioning from one view to another. We will be utilizing Apple’s UINavigationController. I will be using the code from the “Hello World” tutorial that I previously wrote. So if you have not completed it yet, go ahead and do it and come back to this page. (It’s quick I promise). You can view it here.

In this tutorial you will learn:

The first thing we are going to do is change our “Hello World” text to say something that sounds more like navigation. Go ahead and open RootViewController.m. Location the cellForRowAtIndexPath method (it’s the one that you edited to display “Hello World” in the table cell.

Change the line: [cell setText:@"Hello World"] ; to [cell setText:@"Next View"];

Add A New View

We will now add the view that we will be transitioning to. Click on RootViewController.xib and this should open up Interface Builder. We don’t actually need to edit this file. Once inside Interface Builder click on File -> New and select View.

It will add a blank View to your project. For now, we will keep it simple. Go ahead and drag a new Label on to the View. Double click on the label and change the text to whatever you want. I set mine to View 2 (I know, not very imaginative).

Let’s save the view. Click File -> Save. Call it View2. Make sure that you save it inside your Hello World project’s directory. It may want to save it somewhere else by default.

Next, you will see a screen asking you if you want to add the View to your project. Check the box next to Hello World and click Add.

Close Interface Builder. Drag the View2.xib file into the Resources folder, if it didn’t appear there by default (this will help maintain organization).

Add A View Controller

Now we need to create a ViewController class. This class will be used to connect the view that we just created to our code. Inside of Xcode click File -> New File… Select UIViewController subclass and click Next.

Name it View2ViewController and make sure “Also create “View2ViewController.h” “ is checked. Click Finish to continue. This will add the new ViewController to your project.

For organization sake, drag your View2ViewController.h and .m files into the Classes folder if they didn’t appear there to begin with.

Set Up The Transition To The New View

Open up RootViewController.h and add the following code:

This code should be pretty self explanatory, but I will explain it anyway. The import statement #import “View2ViewController.h” gets the header file of the ViewController that we created and allows us to create new instances of it.

Next, we declare a variable called view2ViewController which is of the type View2ViewController. One thing that I want to point out is the first part starts with a capitol “V” which is the type of object that we are declaring. The second part starts with a lower case “v“. This is our variable name that we will use to reference our ViewController object. Finally, we make our variable a property to set additional information.

Now, open up RootViewController.m and add the following code underneath @implementation RootViewController. This creates default “getter” and “setter” methods for our view2ViewController property.

Next find the function didSelectRowAtIndexPath. It may be commented out. If it is, go ahead and uncomment it. This method gets called (automatically) every time a table cell gets tapped. Notice that it takes an indexPath. This will be useful later on when I show you how to populate a UITableView with an NSArray. We will ignore it for now.

Add the following code to the method.

First we check to see if self.view2ViewController is null. This will happen the first time the user presses on the table cell. After this, the viewController gets stored in memory to optimize performance. Next we create a new instance of a View2ViewController and set it to our view2ViewController. Remember to pay attention to a capitol “V” verses a lowercase “v”. After we set this viewController to our viewController, it should be released. Remember, objective-c does not have a garbage collector, so we need to clear all of our unused objects from memory.

Finally, the last line of code is what actually transitions our view to the newly created view. The navigationController object is a stack that contains viewControllers. The view at the top of the stack is the one that gets rendered. So all we are doing is pushing a viewController onto this stack. There last part animated:YES, tells the compiler that we want an animated transition to the next view.

Connect The View To Code

Before this code will execute, we must connect the code that we just wrote to the view we just created. Double click on View2.xib to open it up in Interface Builder. We need to associate our View2ViewController class object with the view so click on the File’s Owner object and then click Tools -> Identity Inspector.

Click the dropdown next to class and select View2ViewController.

Next click anywhere on your view to select it. Click Tools -> Connections Inspector. Click in the circle next to New Referencing Outlet, drag it to the File’s Owner object and release it. The word view will popup. Go ahead and click on it.

Close Interface Builder. You can now click Build and Go. When you click on the words “Next View”, you will see the screen transition to your new view. There is still one thing missing. There is no back button in the NavigationController at the top. Apple actually adds this for us, but we need to set a title on our main view.

Adding The Back Button

Close the iPhone Simulator and open RootViewController.m. In the viewDidLoad method (gets called when the view is first loaded) add the following code.

Since RootViewController extends Apple’s class UITableViewController, it comes with a title property. You can set this to anything you want. I have set it to the string “Hello”. Now click Build and Go and you are done. Here are a few screenshots.

When you click on “Next View” it should transition to:

Notice the back button at the top with the text “Hello”. If you press it, your view will be popped from the NavigationController stack and the previous view will be shown. If you have any problems/questions/comments post them in the comments. I’m pretty good about answering them as it emails me when you do so and I receive them on my iPhone.  If you have any problems, you can download the source code here Hello World Views Source.  Happy iCoding!

iPhone Programming Tutorial - Connecting Code to An Interface Builder View

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!

iPhone Programming Tutorial - Beginner Interface Builder Hello World

In my last tutorial UITableView Hello World I said that there are many ways to write a “Hello World” tutorial for the iPhone.  Here is one using Interface Builder. Last time, I demonstrated a simple way to populate one cell in a UITableView with some text.  Today’s tutorial is even simpler.  I will show you how to work with Interface Builder to create a simple layout for you application.  In fact, you won’t write any code at all! In my next tutorial, I will detail how to interface with your UI components in code.

In this tutorial you will learn:

Create a New View Based Project

Let’s start by opening up XCode and Creating a new View-Based Application.  Do this by clicking on
File > New Project. Make sure that Application is highlighted under iPhone OS and select View-Based Application. Name this project HelloWorldViews.

So at this point, Apple has added some default files to get us started.  They have added the main window for us to edit along with the code to launch the window.  Now in iPhone terms, each window is called a View.  Since you can only see one view at a time, you will need to create a new view for each screen in your application.  In this tutorial, we will be sticking to editing the view Apple has provided us.  In later tutorials, I will go into how to add new views and transition between them.  Go ahead and click Build and Go.

Opening the iPhone Simulator

The program should compile and launch the iPhone Simululator. Your screen should look something like this.

Not very interesting right? Excuse my crappy screenshot.  So let’s add some UI components to our view to make it more interesting.  To do this we will be editing HelloWorldViewsViewController.xib . A file with the .xib extension is known as a nib file.  These files open with Interface Builder and are where you define the look and feel of your application.  Apple is nice enough to have provided us with one.

Adding UI Elements to You Home Screen

Once you open Interface Builder, you should see a few different windows… You should see a blank window that has the same dimentions as the iPhone that says View up in the top.  If not click the View icon in the smaller box.  This is the main window we will be editing.

To the right, you should see a tool box that contains many different UI components.  Most of them should look familiar if you have ever used an iPhone application.  So let’s add a few of them to our view.  Just click on the one’s you want and drag them on to your view. Make sure you at least use a Label.  For this tutorial, I have used a Label, Search Bar, and a Tab Bar.  Notice when you drag the search bar and tab bar onto the view, they size correctly to the screen.  Also, if you move the items around, you will see blue lines that guide you.  These are in place to help you line up components and center them.

After you have added the label, click on it.  Now let’s open the Attributes Inspector to change the text of the label.  To do this click Tools > Attributes Inspector. At the top of the Attributes Inspector you should see a box labeled Text. If you don’t click on the label again to select it.  Put whatever you would like the label to say in that box.  I put “Hello World”.  You can update other properties of the label including color and font using the Attributes Inspector.  You may need to resize the Label to accommodate your new text.  To do this click on the label and you will see little boxes around it that you can drag to resize the text area.

After you are done, your interface should look something like this:

Now press Apple-S to save this file.  We are done with Interface Builder so you can close it.  Your application should now be ready to execute.

Executing the Code

Go ahead and click Build and Go again to launch the iPhone Simulator. Your screens should look something like this:

There you have it! A simple iPhone application without writing a line of code. If you click in the search box, the iPhone will automatically pull up the keyboard.  Thank you for reading this tutorial and I hope that you have learned something.  In my next tutorial, I will show you how to use code to interface with our UI components.  If you have any questions, feel free to leave them in the comments. Happy iCoding!