iPhone Programming Tutorial – Creating a ToDo List Using SQLite Part 2

September 2nd, 2008 Posted by: - posted under:Tutorials

This tutorial is part 2 in our series of creating a to-do list. I will assume that you have completed the following tutorial and its prequisites.

I will be using the code produced from that tutorial as a base for this one. When you are finished with this tutorial, your application will look something like this:

In this section, I will not only teach you how to display the SQL data in UITablewView, but I will be detailing how to display it in multiple columns with images and text. For this tutorial, you will need to download the following images.

We will be using these images to denote the priority (Green = low, Yellow = medium, Red = high).

Bring Your Code Up To Speed

Before we begin, we need to add some code to the Todo.h and Todo.m class to support the priority field in the database. Open up Todo.h and add the following code:

All that is new here is the added NSInteger priority property. We will be using this to get and set the priority for a given todo object. Next, open Todo.m and add the following code.

The first line that has changed is the synthesize line. We added our priority property to allow XCode to create the getter and setter methods for it. Next, you will notice that the sql statement has changed slightly. We are now getting the priority in addition to the text from the todo table. Finally, we set self.priority property to the selected priority value from the todo table. This is done by using the sqlite3_column_int method. We pass the init_statement and the number 1. 1 being the index of the sql array for which the priority data is contained.

Add Images to Your Project

Download the images above and save them to your project directory. Inside of your project, right click (control-click) on the Resources folder and click Add -> Existing Files… Browser for the images, select all of them and click Add. Check the box that sais “Copy items into destination group’s folder (if needed)”. Click Add. The image files should now appear inside of your Resources folder.

Create a UITableViewCell Subclass

To display data in columns within a UITableView, we have to create our own cell class that defines the type of data we want to display. By default, Apple provides us with a simple cell object that can only display one column of text. Normally, this is fine as it will work for a wide variety of applications. Since we require 3 columns for this tutorial, we need to wrap our own cell object.

Click File -> New File… and select UITableViewCell. Click Next.

Name this file TodoCell and make sure this that the box that sais “Also create TodoCell.h” is checked.

This will create a “barebones” UITableViewCell object with some basic methods already filled out. Let’s add some properties to this class. Open up TodoCell.h and add the following code.

Let’s take this line by line…

First, we see a Todo object being declared. Each cell will know which Todo item is associated with it. This will help out when updating the data in each cell. Next, we see 2 UILabels and a UIImageView. To understand why these components are needed, here is a screenshot of how each cell will look.

We see the “Green Dot” which is an image being rendered by a UIImageView. The word “low” and “Take out the trash” are both UILabels. After they are declared, we simply create them as properties. Notice that we are NOT creating a property for the Todo object. We will not be synthesizing it either. This is because we want this variable to be private. Setting this variable requires some additional code so we don’t want any code writer to simply be able to say cell.todo = foo; You will see why this is so further on in this tutorial.

Below this are some method declarations. First we see the method “imageForPriority”. We will be using this method to decide which image (green, red, yellow) gets displayed for a given priority. Next, we see the “getter and setter” methods for the todo object. As I explained above, the setter will contain additonal code besides assigning the todo object.

Now open up TodoCell.m. We will be writing quite a bit of code in here so I will break it up the best I can. First, add the following code to create some of the initialization:

Ok, some new stuff here. First, we see 3 static UIImages. These will hold reference to each of the three images (red, green, yellow). Since we only need to allocate them once, we make them static. Static means that they will be associated with the class not the instance. So we can make as many TodoCells as we want but only 3 UIImages will be created. On the next line there is a private interface. This allows us to declare a private method that no one else can use except this class. Following this is the synthesize line. Notice again that we are NOT synthesizing the todo object.

Looking at the initialize method… All that is going on here is we are intanciating each of our UIImages with the correct image for a given priority. This initialize method will get called once when the first instance of the todocell class is built. Moving on… Add the following code: (Note: it might be small and hard to read. If this is the case, click on the image to open it and the text will be full size)

This is the initialiazation method for any UITableViewCell. First, we need to call the super classe’s (UITableViewCell) initWithFrame to ensure that the underlying components of the cell get set up properly. Next, we get a reference to the contentView. The contentView is the view for each cell. We will be adding all of our UI components to this view.

The next 3 lines initialize a UIImageView and add it to our view. Notice that we are populating it with the priority1Image. This will just be a dummy placeholder until we update it.

Following this, we initialize the todoTextLabel. This label will display what it is we need “to do” such as “Take out the trash”. There is a method that we will be calling called “newLabelWithPrimaryColor”. This is a method I will detail a little further down. What it will do is build a new label with the attributes that we specify when we call it. This method was taken directly from Apple’s “Seismic XML” sample code. It’s pretty handy. After this gets called, we simply add the new label to our view and these steps get repeated for the todoPriorityLabel.

Finally, the method “bringSubviewToFront” is called on the priority UIImageView. This method is used in case there is text that gets near the image. It will cause the image to appear above the text. You can use this for layering your UI components.

Still with me? Good… now let’s add the following “getter” and “setter” methods for the todo object.

The first method todo is simple. All it does is return our todo object. The setTodo is a little more involved…

First, we set the incoming (newTodo) to our classe’s todo object. Next, we update the UITextLabel so we can display the detailed todo information. Following this we set the image of our UIImageView by calling the method imageforPriority. I will detail this method further down in this tutorial but all it does is return an image for a given priority. Last, we have a switch statement. The syntax of a switch statement is the same in objective C as it is in most languages. If you don’t know what a switch statement is Google it. Based on the priority of the newTodo, the priority label gets updated with one of three words (High, Medium, Low). The [self setNeedsDisplay] tells the cell to redisplay itself after this todo has been set.

Now, let’s add the code that lays out the cell.

This method gets called automatically when a UITableViewCell is being displayed. It tells the UITableView how to display your cell. The define statements are similar to define statements in C. The reason we are coding like this is because we can tweak these variables to get the display to our liking. First, we call the layoutSubviews of the super class. Next, we get a reference to the contentView.bounds. This variable will allow us to figure out how much drawing area we have and allow us to line objects up properly.

The if(!self.editing) part is not neccessary but is good practice. You would use this if you allowed editing of your cells. This code is a little tough to explain by typing, but I will do the best that I can. First, we declare our right-most column. This is done by making a frame to hold the content. This column will hold the text of the todo item. Most of the code here is just positioning. You can play with these numbers and see how it moves stuff around. Once all of the positioning code is completed, the frame of our todoTextLabel gets set to this newly created frame. This is done for each of our UI components. You can lay them out however you like, as I may not have the best layout.

We have one more method to override. It’s the setSelected method. Go ahead and add the following code.

This method gets called when the user taps on a given cell. We need to tell the cell how to behave when it gets tapped on. This method should look pretty straight forward. First, we call the setSelected method of the super class. Next, we update the background color depending on whether or not the cell was selected. Finally, the labels get set to a white color if the cell gets selected. This is to contrast the blue color that the background becomes when the cell is selected.

This last 2 methods that I want to talk about are the helper methods that we used earlier in the code. Add the following methods to your code.

newLabelWithPrimaryColor

This method got called when we were initializing our UILabels. It takes a few parameters that should be pretty self explanatory. Looking through the code, we first see the font being initialized with the size that we specified. If bold was specified this is also accounted for. Next, we instantiate a new UILabel and give it some properties. Finally, this newly created UILabel gets returned.

imageForPriority

This method is actually quite simple. It simply takes a priority and returns the UIImage that is associated with that priority. Notice the default clause. I decided to handle it like this instead of doing “case 1″ to handle all other cases. For whatever reason, if there is ever a priority that is not 1,2 or 3 it will, by default, have low priority.

Now that we have created our UITableViewCell, we need to display it in the table. Open up RootViewController.m and add the following import statement. This will allow us to use our TodoCell object.

Now find the numberOfRowsInSection method and add the following code

I’m not going to really go over this, as this is almost the exact same code as in the Fruits example. Basically, we are returning the number of todo items.

Now for the magic…We will now add our TodoCell to allow it to be displayed. Find the cellForRowAtIndexPath method and add the following code.

This code is fairly similar to the default code that Apple has provided us. The first change is we are instantiating our TodoCell object. We are creating it with the initWithFrame method and passing our identifier to it. Next, we get reference to the application’s appDelegate and use it to look up the todo item at the given index. This should be familiar. Finally, we set the todo item of the cell to the todo item at the row index and return the cell. That’s it! Go ahead and click the Build and Go icon and see your todo list come to life. Here is a screenshot of what your app should look like.

That concludes part 2 of this tutorial. Join me next time as I show you how to display detailed todo info using some new UI controls that we haven’t seen yet. As always, post your questions and comments in the comments section of the blog. Download The Sample Code

Happy iCoding!