WHAT YOU WILL LEARN IN THIS CHAPTER
How to manually add a Table view to a View, and wire the data source and delegate to your View Controller
How to handle the various events in the table view to populate it with items
How to handle the various events in the Table view so that users can select the items contained within it
How to display text and images in the rows of the table view
How to display the items from a property list in a table view
How to group the items in a table view into sections
How to add indexing to the table view
How to add search capabilities to the table view
How to add disclosures and checkmarks to rows in the table view
One of the most commonly used views in iPhone applications is the Table view. The Table view is used to display lists of items from which users can select, or they can tap it to display more information. Figure 10-1 shows a Table view in action in the Settings Application.
In Chapter 8, you had your first taste of the Table view when you developed a Navigation-based Application project. That chapter didn't fully dive into how the Table view works, and a lot of details were purposely left out. The Table view is such an important topic that it deserves a chapter on its own.
Hence, in this chapter, you examine the Table view in more details and understand the various building blocks that make it such a versatile view.
The best way to understand how to use a table view in your application is to create a new View-based Application project and then manually add a Table view to the view and wire it to a View Controller. That way, you understand the various building blocks of the Table view.
Without further ado, use the following Try It Out to create a new project and see how to put a Table view together!
You can display a header and footer for the Table view by simply implementing the following two methods in your View Controller:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{//---display "Movie List" as the header---return @"Movie List";
} - (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {//---display "by Denzel Washington" as the footer---return @"by Denzel Washington";
}
If you insert the preceding statements in the TableViewExampleViewController.m
file and rerun the application, you see the header and footer of the Table view as shown in Figure 10-5.
In addition to text, you can display an image next to the text of a cell in a Table view. Suppose you have an image named apple.jpeg
in the Resources
folder of your project (see Figure 10-6).
You can simply drag and drop an image to the Resources folder of Xcode. When prompted, ensure that you save a copy of the image in your project.
To display an image next to the text of a cell, insert the following statements that appear in bold into the tableView:cellForRowAtIndexPath:
method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; //---try to get a reusable cell--- UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //---create new cell if no reusable cell is available--- if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } //---set the text to display for the cell--- NSString *cellValue = [listOfMovies objectAtIndex:indexPath.row]; cell.text = cellValue;UIImage *image = [UIImage imageNamed:@"apple.jpeg"];
cell.imageView.image = image;
return cell; }
Press Command-R to test the application and you see that the image is displayed next to each row (see Figure 10-7).
Notice that the UITableViewCell
object already has the imageView
property. All you need to do is to create an instance of the UIImage
class and then load the image from the Resources
folder of your project.
So far, you have seen how to populate the Table view with items by ensuring that your View Controller conforms to the UITableViewDataSource
protocol. This protocol takes care of populating the Table view, but if you want to select the items in a Table view, you need to conform to another protocol, UITableViewDelegate
.
The UITableViewDelegate
protocol contains events that allow you to manage selections, edit and delete rows, and display a header and footer.
To use the UITableViewDelegate
protocol, modify the TableViewExampleViewController.h
file by adding the statement in bold as follows:
#import <UIKit/UIKit.h>
@interface TableViewExampleViewController : UIViewController
<UITableViewDataSource,
UITableViewDelegate>{
}
@end
Strictly speaking, if you have connected the delegate
outlet to the File's Owner item previously (see Figure 10-8), you don't need to add the preceding statement (UITableViewDelegate
). Either you write the preceding statement or connect the outlet in Interface Builder. However, doing both doesn't hurt.
The following Try It Out shows how you can allow users to make selections in a Table view.
Another event in the UITableViewDelegate
protocol is tableView:indentationLevelForRowAtIndexPath:
. When you handle this event, it is fired for every row that is visible on the screen. To set an indentation for a particular row, simply return an integer indicating the level of indentation:
- (NSInteger)tableView:(UITableView *)tableView
indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
return [indexPath row] % 2;
}
In the preceding example, the indentation alternates between 0 and 1, depending on the current row number. Figure 10-10 shows how the Table view looks if you insert the preceding code in the TableViewExampleViewController.m
file.
In the previous sections, you create a View-based Application project and then manually add a Table view to the View window and connect the data source and delegate to the File's Owner item. You then handle all the relevant events defined in the two protocols, UITableViewDelegate
and UITableViewDataSource
, so that you can populate the Table view with items as well as make them selectable.
In real life, the Table view is often used with a Navigation-based Application because it is very common for users to select an item from a Table view and then navigate to another screen showing the details of the item selected. For this reason, the Navigation-based Application template in the iPhone SDK by default uses the TableView
class instead of the View
class.
In addition, you can group items in a Table view into sections so that you can group related items with a header for each section. In the following Try It Out, you learn how to use the Table view from within a Navigation-based Application project. At the same time, you learn how to display items stored in a property list, as opposed to an array.
The list of movies is pretty short, so scrolling through the list is not too much of a hassle. However, imagine that the list contains 10,000 titles spanning 100 years. In this case, scrolling from the top of the list to the bottom of the list can take a long time. A very useful feature of the Table view is its ability to display an index on the right side of the view. An example is the A–Z index list available in your Contacts list (see Figure 10-19).
To add an index list to your Table view, you just need to implement the sectionIndexTitlesForTableView:
method and return the array containing the section headers, which is the years
array in this case:
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { return years; }
Before you run the application, be sure to change the style of the Table view back to Plain. If you set it to Grouped style, the index will overlap with the layout of the Table view.
Figure 10-20 shows the index displayed on the right side of the Table view.
One very common function associated with the Table view is the ability to search the items contained within a Table view. For example, the Contacts application has the Search Bar at the top (see Figure 10-21) for easy searching of contacts.
In the following Try It Out, you will learn how to add search functionality to the Table view.
Because users often select rows in a Table view to view more detailed information, rows in a Table view often spot images containing an arrow or a checkmark. Figure 10-25 shows an example of such arrows.
There are three types of images that you can display:
To display a disclosure or checkmark, insert the following statement that appears in bold in the tableView:cellForRowAtIndexPath:
event:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } // Configure the cell. if (isSearchOn) { NSString *cellValue = [searchResult objectAtIndex:indexPath.row]; cell.text = cellValue; } else { NSString *year = [years objectAtIndex:[indexPath section]]; NSArray *movieSection = [movieTitles objectForKey:year]; cell.text = [movieSection objectAtIndex:[indexPath row]];}
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
return cell; }
You can use the following constants for the accessoryType
property:
UITableViewCellAccessoryDetailDisclosureButton
UITableViewCellAccessoryCheckmark
UITableViewCellAccessoryDisclosureIndicator
Figure 10-26 shows the different types of images corresponding to the three preceding constants.
Of the three image types, only the UITableViewCellAccessoryDetailDisclosureButton
can handle a user's tap event. (The other two images are used only for display purposes.) To handle the event when the user taps the Disclosure button, you need to implement the tableView:accessoryButtonTappedForRowWithIndexPath:
method:
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath { //---insert code here--- // e.g. navigate to another view to display detailed information, etc }
Figure 10-27 shows the two different events fired when a user taps the content of the cell as well as the Disclosure button.
Commonly, you use the Disclosure button to display detailed information about the selected row.
In this chapter, you had a good look at the Table view and how to customize it to display items in the various forms. You also learned how to implement search functionality in the Table view, which is an essential function in real-world applications.
EXERCISES
Name the two protocols that your View Controller must conform to when using the Table view in your view. Briefly describe their uses.
Which is the method to implement if you want to add an index in a Table view?
Name the three disclosure and checkmark images that you can use. Which one of them handles user taps?
WHAT YOU HAVE LEARNED IN THIS CHAPTER
TOPIC | KEY CONCEPTS |
---|---|
Add items to a Table view | Handle the various events in the |
Allow users to select rows in a Table view | Handle the various events in the |
Add images to rows in a Table view | Use the image property of the |
Use a property list with a Table view | Use the following code snippet to locate the property list:
Then use a combination of |
Group items in a Table view in sections | Implement the following methods:
|
Add an index to a Table view | Implement the |
Add disclosure and checkmark images to a row in a Table view | Set the
|
Implement a search in a Table view | Use the Search Bar view and handle the various events in the |