Tuesday, July 10, 2012

UITableView How-To: Part 4 - XIB-Based Cells

Part 1 | Part 2 | Part 3 | Part 5Part 6

 

Up to this point in the series, the focus has been on basic table and data structures. Now let's take a look at customizing the appearance of the table view.

 

I'm not intending to spend much time talking about standard cells, but there actually are a number of ways to customize cells without needing to subclass. UITableViewCell's initWithStyle: method accepts a parameter for which Apple has provided several standard options. You can show text in several places, and you can add images and accessories. Take a quick glance at the Settings app on your phone; those are standard cells. So before you dive into subclassing cells, make sure you are aware of the built-in options. They can save you a lot of time. This post at Cocoa With Love is definitely worth reading.

 

But, let's assume that those standard configurations are inadequate for your awesome table design. Or perhaps you've seen another app that displays lots of crazy things in a table, and you wonder how it was done. Chances are that the answer will be the same either way: custom table cells. Like most visual things in Cocoa, there is a code-based approach and an Interface Builder-based approach. I'm going to focus on using IB, as the layout is significantly easier, although the setup has some nuances. This approach is based on the Apple sample project called TaggedLocations.

 

Overview

Let's take a quick look at the players involved, because the process to set this up is a tad convoluted:

ViewController.h
ViewController.m
ViewController.xib

TableCell.h
TableCell.m
TableCell.xib

 

In the same way that you would reference a button in your view by creating an IBOutlet, the same thing will be done here. So the view controller will have an IBOutlet for the cell:

@property (nonatomic, retain) IBOutlet TableCell *tableCell;

 

In order to do this without causing any build errors, the cell class needs to exist. But this outlet needs to exist in order to to complete the TableCell.xib, so there is something of a chicken-and-egg situation. The basic steps are:

 

1. Create the view controller class
2. Create the cell class
3. Create the IBOutlet in the view controller
4. Design the cell
5. Rewire the table delegate methods to use the cell

 

So there is a fair amount of back-and-forth between the classes, but after you get used to it, it's not so bad. Let's begin…

 

1. Create a view controller. I'm calling this one BasicViewController, but you can use whatever you want. Don't bother getting too hung up with delegate methods for now.

 

2. Add a new file. This will be a UITableViewCell subclass, and it's not immediately clear how to do this. Just choose Objective-C class, and then select UITableViewCell from the pull-down menu:

 

 

Call it CustomTableCell. This will create the .h and .m file, but we want a XIB file, too. So add a new file for that as well. Select User Interface at the side, and then choose a View XIB. iPhone-vs-iPad doesn't really matter, but I tend to go with iPhone.

 

 

Give it the same CustomTableCell name. You should now have .h, .m, and .xib files for CustomTableCell.

 

3. Now create an IBOutlet for the cell in the view controller. You will need @class in the .h file and #import in the .m class. The highlights of what you should wind up with are:

 

// BasicViewController.h
#import <UIKit/UIKit.h>
@class CustomTableCell;

@interface BasicViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
}

@property (nonatomic, retain) IBOutlet UITableView *mainTableView;
@property (nonatomic, retain) IBOutlet CustomTableCell *customTableCell;

 

// BasicViewController.m
#import "CustomTableCell.h"

@implementation BasicViewController

@synthesize mainTableView = ivMainTableView;
@synthesize customTableCell = ivCustomTableCell;

- (void)dealloc
{
[self setMainTableView:nil];
[self setCustomTableCell:nil];
[super dealloc];
}

 

4. Configure the cell. Open up CustomTableCell.xib, as we have some preliminary things to take care of. You should see:

File's Owner
First Responder
View

Select View and delete it. Now go to your Library palette, find the Table View Cell, and drag it to the spot where View was.

 

 

Now we need to change classes. Select File's Owner, and go to the inspector panel for Identity (Cmd-4). Change the class to BasicViewController. Now select the table view cell, and in the inspector change the class to CustomTableCell.

 

 

Now we need to connect the IBOutlet we made earlier. Ctrl-click on File's Owner. Select the customTableCell outlet, and drag that to the CustomTableCell item.

 

 

Hey, wait a second... this isn't my view controller's XIB! You are correct. But the view controller will create this class - it will be the file's owner - so it does make some sense to do this. But don't get carried away. For example, you do see the view outlet, but don't mess with that here as that is being populated in your view controller's XIB. We are doing this for one reason and at this point one reason only: to get access to that cell IBOutlet.

 

There is a lot of customization we could potentially do here, but in the interest of quickly moving along to see this in action, simply drop a couple of a labels onto the cell. We'll come back later to wire everything up.

 

 

5. Configure the table delegate methods. Return to BasicViewController, and for now tell it there are 10 rows. The important change happens in cellForRow:

 

- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CellIdentifier";

CustomTableCell *cell = (CustomTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
[[NSBundle mainBundle] loadNibNamed:@"CustomTableCell" owner:self options:nil];
cell = [self customTableCell];
[self setCustomTableCell:nil];
}
return cell;
}

 

For the most part, this is pretty similar to what we've done before. Instead of a UITableViewCell, we're using a CustomTableCell, so we change the class types to reflect that. We're still asking for an available cell, and if one isn't available then we create one. The creation part is different than we've done before, naturally since we aren't just using code this time.

 

The first thing we do is load the XIB file. We indicate which class, and who should own it. The next thing we do is wave our hands and say there is some black magic happening here. Then we assign the cell property to our cell variable. Hrm, what? How did that get there? Well, let's back up and address that black magic.

 

The documentation has this to say about loadNibNamed:owner:options:

During the loading process, this method unarchives each object, initializes it, sets its properties to their configured values, and reestablishes any connections to other objects.

 

For our purposes, the important part is the last bit.

 

Think about what you do with a normal view controller. You place, say, an image view in IB, you create an IBOutlet for it, and then make the connection in IB. So after you instantiate your view controller, what happens? The XIB is loaded, which means an image view is also instantiated, and this image view is then assigned to your IBOutlet/property. When you go to talk to your image view using the property - [[self imageView] setImage:...]; - the image view is there already.

 

What we're doing here is exactly the same, only splitting things up into separate files. Instead of an image view, it's a table cell, and instead of being in the view controller's XIB, it is in a separate XIB. But the act of loading the XIB causes the outlets to be populated, so we end up with the same result. Black magic indeed.

 

So:
1. We load the XIB file
2. The IBOutlet gets populated with the cell
3. We assign that cell to our local cell variable
4. We clear out the property since we don't need to keep it around

 

Go ahead and run the app at this point, and if you've wired everything correctly, you should see:

 

Configure the cell

 

Let's circle back around and finish up the cell. First of all, we skipped a really important step. Recall what the initializer for a standard cell looks like:

 

cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

 

We pass two parameters: a style, AND a reuse identifier. Now compare to how we just created the cell:

 

[[NSBundle mainBundle] loadNibNamed:@"CustomTableCell" owner:self options:nil];

 

Uh oh, no reuse identifier parameter. That's a problem if we want good table scrolling performance (and we do). I wish Apple would have handled this differently, but what they did is imbed the reuse identifier into the XIB file. So open it back up, and select the cell. Then go to the inspector panel again, Cmd-1.

 

 

It will be blank when you first look at it, so you will need to type it in. The important part here, and one unfortunate aspect of Apple's decision to do this, is that whatever you type in here, needs to match what you type in here:

 

static NSString *CellIdentifier = @"CustomCellIdentifier";

 

So you have to make sure the same thing is typed in 2 places, and if you screw up either one then you won't recycle cells. This will hurt scrolling performance. I really wish Apple had gone with more of an initWithNibName:bundle:reuseIdentifier: approach for these cells. Oh well.

 

Let's add some properties to the cell so that we can talk to the labels.

// CustomTableCell.h
@interface CustomTableCell : UITableViewCell
{
}

@property (nonatomic, retain) IBOutlet UILabel *redLabel;
@property (nonatomic, retain) IBOutlet UILabel *greenLabel;

 

// CustomTableCell.m

@implementation CustomTableCell

@synthesize redLabel = ivRedLabel;
@synthesize greenLabel = ivGreenLabel;

....

- (void)dealloc
{
[self setRedLabel:nil];
[self setGreenLabel:nil];
[super dealloc];
}

 

Standard stuff here. Where it gets tricky is actually making the connections in IB. You are probably accustomed to dragging from File's Owner to establish IBOutlet connections. Ah, but remember which class we're dealing with here. File's Owner is the view controller, but we are adding these IBOutlets to the cell. So you can drag from File's Owner all that you want, but you won't be able to create the links. You have to drag from the cell class to the labels:

 

 

Now let's head back to the view controller and put some data in the labels. I'm not going to bother setting up any data; refer to Part 3 for some thoughts on how to arrange your data for this purpose. For now, just drop in something so that you can see different text in each field:

 

   ...

NSUInteger row = [indexPath row];
[[cell redLabel] setText:[NSString stringWithFormat:@"Red %d", row]];
[[cell greenLabel] setText:[NSString stringWithFormat:@"Green %d", row]];

return cell;
}

 

With standard cells, you are talking to [cell textLabel] or [cell detailTextLabel]. Same idea, just using the properties that you've created.

 

Your cell is a blank canvas ready to be customized to your heart's delight. Want 5 labels? Good. Want 10 images? Great. Go nuts.

 

This is turning into a longer post than I thought, and I still have a lot to talk about. So I'm going to split this up into 2 posts. Tune in later for the sequel.

 

TableViewTutorial_Part4.zip

UITableView How-To: Part 3 - Multiple Sections

Part 1 | Part 2 | Part 4 | Part 5Part 6

 

In my experience so far, people seem to have a knack for making multi-section table views harder than they really are. The key to simplifying things is to prepare your data in such a way that pain is removed from your table delegate methods. If your delegate methods are nothing but switch/case statements or a ton of if/else if statements, then you've likely given yourself a pretty good headache.

 

Let's quickly revisit some key elements from Part 1. To determine the number of rows, we did this:

 

NSInteger rows = [[self contentsList] count];

 

...and to get the information to show in the cell, we did this:

 

NSString *contentForThisRow = [[self contentsList] objectAtIndex:[indexPath row]];

 

We count up everything we have, and then we use the row parameter to extract the specific piece of information. That's fine when we have one continuous list, but if you want a sectioned display, then you don't have one continuous list anymore. And this is true regardless of the display type.

 

There are two default display options for table views. Plain:

 

 

And grouped:

 

This is purely visual fluff. You can go back to the exercise in Part 1 if you want and flip it to grouped, and nothing else needs to change. The easiest way to manage this sectioned/grouped appearance is to group your data as well. The long list of 500 names that you have in your address book needs to be broken up into pieces.

 

How you actually get your data broken up is a programming exercise that I'm not going to go into here. There are lots of ways to do it, and the 'correct' approach will depend on your actual data and your specific needs. What I will show here are two different structures that you can use that simplify the delegate methods considerably. They are:

  • An array of arrays
  • A dictionary, and an array of keys

But first we need to introduce a delegate method that we haven't seen or used yet. In Part 1, we answered the question "how many rows in this section". The second half of that question is important, as we never indicated how many sections there are. This is yet another question the table view can ask, and it is:

 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

 

This is an optional method, as evidenced by the fact we didn't use it in the previous exercises. But clearly the table works without it, so what gives? As noted in the documentation, the default value is 1. So the tables we've seen so far actually were sectioned table views, just with only 1 section.

 

Just like we did for the number of rows, we should probably base the answer on a calculation. If you have a simple table that will only ever have 2 sections, then by all means go ahead and hard-code a 2. But if the number could change, it needs to be related to your data somehow. More on that in a moment.

 

For now, I'm going to take the code from Part 1, remove a couple of colors, and then set the number of sections to 3.

 

 

Notice that the rows repeat; I have 3 groups of the same thing over and over again. Why is that? Well, let's remember how we collected the data to display:

 

NSString *contentForThisRow = [[self contentsList] objectAtIndex:[indexPath row]];

 

Using the row alone, we pull data from the array. Why does it repeat? Because the row numbering starts over for each section. Section and row numbers look like this:

 

Section 0
Row 0
Row 1
Row 2
Section 1
Row 0
Row 1
Row 2
Section 2
Row 0
Row 1
Row 2

 

Three sections, so the table view asked for something to display in Row 0 three times. And that's exactly what we gave it: the first item in the array, 3 separate times.

 

This is why arranging the data in a particular way is important.

 

How do we find our way around in the table? Well, we've already seen this:

 

[indexPath row]

 

Now we also need to use this:

 

[indexPath section]

 

NSIndexPath actually does a lot more than this, but for most iPhone purposes it is used to describe a section and row location in a table view. In Part 1, we used the row parameter to select an item from the array. We are still going to do that, but we will now use the section parameter to decide which array.

 

Array of Arrays

 

As previously stated, the key is arranging your data in a way to facilitate a sectioned table view. We'll keep the same contentsList array that we had before, but we'll change the contents. Before, it contained only strings. Now, it will contain arrays. Those arrays will contain strings.

 

NSArray *firstSection = [NSArray arrayWithObjects:@"Red", @"Blue", nil];
NSArray *secondSection = [NSArray arrayWithObjects:@"Orange", @"Green", @"Purple", nil];
NSArray *thirdSection = [NSArray arrayWithObject:@"Yellow"];

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:firstSection, secondSection, thirdSection, nil];
[self setContentsList:array];
[array release], array = nil;

 

Same basic idea as before, but we've added some structure. We need to make adjustments to the delegate methods to account for this new structure. First, our new delegate method for number of sections:

 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSInteger sections = [[self contentsList] count];

return sections;
}

 

This is the same calculation we started with, but now we are answering a different question. In Part 1, this calculation was for the number of rows. Now it is the number of sections. So far so good. Now we need to define the number of rows. You'll note I set up the arrays so that each one has a different number of objects. This is to help reinforce that these numbers probably shouldn't be hard-coded. You want everything to work whether your array has 5 objects or 500 objects.

 

In Part 1, the number of rows was the number of items in the main array. That is no longer the case. We must first identify which sub-array we're interested in, and then count that sub-array. There was a parameter we ignored before:

 

- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section

 

How many rows are in this section? We've told the table how many sections there will be, and the table will now call this method for each section, passing in the appropriate value. We'll use this to identify which array we want.

 

NSArray *sectionContents = [[self contentsList] objectAtIndex:section];

 

For the first section in the table, I want a reference to the first sub-array in the main array. Second array for the second section, and so on. The number of rows is then the count of this sub-array.

 

- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
NSArray *sectionContents = [[self contentsList] objectAtIndex:section];
NSInteger rows = [sectionContents count];

return rows;
}

 

So it is the same idea as what we did before, we just have to count a different array each time. It's not horribly complicated, you just have to plan for it.

We use this same concept again to determine what the row contents are. The only difference is that we get to the section value through the indexPath parameter.

 

NSArray *sectionContents = [[self contentsList] objectAtIndex:[indexPath section]];

 

Now we do the same thing we did before, using the row parameter, but using this array instead of the main one.

 

- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *sectionContents = [[self contentsList] objectAtIndex:[indexPath section]];
NSString *contentForThisRow = [sectionContents objectAtIndex:[indexPath row]];
...

 

After this, nothing is different than what was done in Part 1. Feed this string into the cell, and you should be good to go. If everything is wired up correctly, then you should see:

 

That's really all there is to it. Once you have this structure in place, you can add or remove as many colors as you want - to/from each section - and you don't have to mess with the delegate methods anymore. We added 1 delegate method, and 1 line of code each to two existing delegate methods (plus the extra stuff for setting up the data) vs. what we had in Part 1. Easy!

 

A dictionary, and an array of keys

 

Again there are many possible ways to structure your data, so I offer this next one merely as another example. But it is handy if you want even more data in your table view, specifically headers. If you look at the address book, you'll see letters for each group of people - A's, B's, etc. - and this data has to be set up somewhere, somehow.

 

Dictionaries store data using keys, typically strings. So you store something by name, and you retrieve something by name. Those names can be easily used as section headers. The problem is that dictionaries do not have order. There is no first object, second object, etc., and tables really like for things to be in order. So in addition to using the dictionary, we will continue to use an array to provide order.

 

Again, how you set up the data is pretty important. So let's start with the basics, we have a dictionary and an array:

 

@interface DictionaryViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
}

@property (nonatomic, retain) IBOutlet UITableView *mainTableView;
@property (nonatomic, retain) NSMutableArray *sectionKeys;
@property (nonatomic, retain) NSMutableDictionary *sectionContents;

 

I've kinda shown my hand here with the names. The dictionary will hold the contents of each section, and the array will hold the keys. The contents will be arrays, just like in the previous example. We're just going to access them in a different way. The data is prepared like so:

 

NSMutableArray *keys = [[NSMutableArray alloc] init];
NSMutableDictionary *contents = [[NSMutableDictionary alloc] init];

NSString *colorKey = @"Colors";
NSString *clothingKey = @"Clothing";
NSString *miscKey = @"Misc";

[contents setObject:[NSArray arrayWithObjects:@"Red", @"Blue", nil] forKey:colorKey];
[contents setObject:[NSArray arrayWithObjects:@"Pants", @"Shirt", @"Socks", nil] forKey:clothingKey];
[contents setObject:[NSArray arrayWithObjects:@"Wankle Rotary Engine", nil] forKey:miscKey];

[keys addObject:clothingKey];
[keys addObject:miscKey];
[keys addObject:colorKey];

[self setSectionKeys:keys];
[self setSectionContents:contents];

[keys release], keys = nil;
[contents release], contents = nil;

 

This should look reasonably similar to what we did before. We've added a dictionary, and you add data to a dictionary differently than you do an array, but otherwise it is the same idea. If you're paying attention to details (and as a programmer, you should be) then you'll notice that the order I added the keys is different than the order I added the arrays. I only did this to illustrate that the order of the dictionary doesn't matter, and the order of the array is what will be driving the table.

 

After this, the approach is pretty similar to what we did before. We need to tell the table how many sections:

 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSInteger sections = [[self sectionKeys] count];

return sections;
}

 

Since the dictionary and the array have the same number of objects, I could have counted either one. But typically you'll want to use the array. If I'm testing various arrangements, I will often make the contents the same regardless, and observe differences by messing with the keys. Don't want colors today? Just don't add the key to the array, and nothing else needs to change.

 

Now we need to provide the number of rows. This is the same approach as last time, just going through the dictionary.

 

- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
NSString *key = [[self sectionKeys] objectAtIndex:section];
NSArray *contents = [[self sectionContents] objectForKey:key];
NSInteger rows = [contents count];

return rows;
}

 

We grab the key using the section parameter, then grab the sub-array using that key. Same thing for the row contents:

 

- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *key = [[self sectionKeys] objectAtIndex:[indexPath section]];
NSArray *contents = [[self sectionContents] objectForKey:key];
NSString *contentForThisRow = [contents objectAtIndex:[indexPath row]];
...

 

At this point, we've essentially recreated the first example. But we went this way for a reason, and that reason is section headers. There is another delegate method:

- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section
{
NSString *key = [[self sectionKeys] objectAtIndex:section];

return key;
}

 

We've already seen how to grab the key, so we simply do that and use the key as the header.

 

Food For Thought

 

Usually when I see rookie attempts at multi-section tables, there is a lot of code like this:

 

if (section == 0)
{
...
}
else if (section == 1)
{
...
}
...

For a simple structure: Ok, it probably doesn't make a big difference
For a complex structure: No, just no

 

This is paving the way for a modification nightmare. We've only looked at cellForRow so far, but you're going to do the same thing in didSelectRow (we'll get to that later), too. If you decide to rearrange things, you've got to remember everywhere that it is supposed to change, and of course you'll forget, and things will go badly.

 

You'll notice that the code I've posted so far doesn't look anything like this. The logic is provided up front by the structure of the data, so it isn't necessary to complicate the delegate methods. All they have to do is select data, no other decisions are necessary.

 

But let's assume for a moment that there is indeed a reason to further customize in the delegate methods. Let's say that all of the text in the colors section should be red. No problem. But you still don't want to hard-code like this. What happens if tomorrow you decide that colors should be section 5? Then you have to change all of these statements.

 

There isn't really a good option for the array-of-arrays case, so this may be a good vote in favor of the dictionary approach. Rather than hard-coding the section number, I can be flexible according to the section key.

 

if ([key isEqualToString:@"Colors"])
{
// Make them red
}
else
{
// Make them black
}

 

Now you've got a condition that will trigger correctly regardless of the order of the data. And if today you are testing without colors, no problem. Drop the key, and this condition will never trigger.

 

Once you get comfortable with the basic concepts here, you may want to take a look at a post I made a long time ago: Taming Table Views. There, I show the structure of a custom model class that I use all of the time with sectioned table views. This would be used with the array-of-arrays approach, but instead -of-arrays, it would be -of-DisplaySections. It has a field for the header, a field for the letter index, a field for behind-the-scenes stuff if needed, and it has an array property for the contents. A couple months after I wrote that, I discovered that Apple has a similar class (actually a protocol) for working with CoreData stuff called NSFetchedResultsSectionInfo.

 

One last comment regarding searching. If all you do is take the code in these samples and apply them to your project from Part 2, then searching will not work. Keep in mind the way we've changed the structure. It used to be an array of strings. It is now an array of arrays of strings. So you will have to adapt the search routine to this new structure. It is along the same lines as what we've done above in the delegate methods, so you should be able to figure it out.

 

TableViewTutorial_Part3.zip

UITableView How-To: Part 2 - Search

Part 1 | Part 3 | Part 4 | Part 5Part 6

 

If you have a lengthy list of data, you should provide the ability for your users to search through that data. Starting with OS 3.0, Apple made integrating search into table views easy enough that there really isn't a good reason not to include it.

 

This post is based heavily, if not entirely, on Apple's sample project called TableSearch.

 

UISearchDisplayController

 

The search UI that Apple provides is basically a table view with a search bar. They provide some pretty animations, such as sliding the search bar up to cover up the navigation bar (handy for maximizing available space, especially in landscape). The search table view is overlaid onto your existing view, so both your original table and the search table need data. The principles of delegate and data source as discussed in the last post still apply.

 

In addition to creating the controller itself, Apple also gave UIViewController a searchDisplayController property, which makes it easier to access. This obviously isn't populated by default, but be aware that it exists.

 

 

Data

 

Say you have a list of 10 items. The user performs a search, and only 2 items meet the criteria. Now think back to our datasource and delegate methods. We are answering a lot of questions about the table: how many sections, how many rows, what cell should be displayed (and what should the cell contain)? We still have to answer those questions, only now there are two tables involved. Even if there was only a single table, something would still have to be done with the data. There are two basic approaches you can take: 1) Remove items that don't match, or 2) Create a whole new list containing only items that do match. If you go with #1, you need some way of restoring the full list. So really, in either case, you are talking about 2 sources of data: the full list, and the search results. Since a separate table is involved for the search results, #2 probably makes more sense, and is what Apple shows in their demo.

 

Step Up To The Bar

 

We'll start with the easiest part of this project. Open up the view controller XIB in Interface Builder, and make sure you can see the table view. Find the Search Bar And Search Display Controller item in the library.

 

 

Do note that this is a separate choice from the standalone search bar. You can certainly roll your own solution using just the bar, but the controller is what makes the work relatively easy. So be sure to grab the one with the little orange circle.

 

In order to get the search bar to scroll with the table, we are going to add it as the table's header. Grab the library item, and drag to the upper portion of the table view. You should see a blue highlight, which is your confirmation that you will get the header.

 

 

A number of things happen automatically when you do this. Let's take a quick look at the object list:

 

 

Even though we didn't directly place it there, the Search Display Controller has been added. If we inspect the connections...

 

 

…we see a whole host of additions. The searchDisplayController property on the UIViewController has been populated. The necessary delegate and datasource connections have been made for the search controller, and the delegate has also been specified for the search bar itself. Not bad for one drag-n-drop operation. We are now done with IB, the rest is handled in code.

 

Changes to .h

 

Here is the end result, then I'll explain what's going on.

 

//  SampleViewController.h

#import <UIKit/UIKit.h>

@interface SampleViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate, UISearchBarDelegate>
{
}

@property (nonatomic, retain) IBOutlet UITableView *mainTableView;
@property (nonatomic, retain) NSMutableArray *contentsList;
@property (nonatomic, retain) NSMutableArray *searchResults;
@property (nonatomic, copy) NSString *savedSearchTerm;

- (void)handleSearchForTerm:(NSString *)searchTerm;

@end

 

First, we conform to the UISearchDisplayDelegate and UISearchBarDelegate protocols. Same idea as what we did for the table view previously.

 

Next we declare a couple of new instance variables and properties. The searchResults array will hold items that match the search criteria. The savedSearchTerm is something that Apple shows in their sample, and they use it to restore the search when returning to this screen.

 

Finally, we declare a method that will do the grunt work of searching through the data.

 

Changes to .m

 

We'll start at the top and work our way down. First, synthesize properties and handle memory management duties.

 

@implementation SampleViewController

@synthesize mainTableView = ivMainTableView;
@synthesize contentsList = ivContentsList;
@synthesize searchResults = ivSearchResults;
@synthesize savedSearchTerm = ivSavedSearchTerm;

- (void)dealloc
{
[self setMainTableView:nil];
[self setContentsList:nil];
[self setSearchResults:nil];
[self setSavedSearchTerm:nil];

[super dealloc];
}

- (void)viewDidUnload
{
[super viewDidUnload];

// Save the state of the search UI so that it can be restored if the view is re-created.
[self setSavedSearchTerm:[[[self searchDisplayController] searchBar] text]];

[self setSearchResults:nil];
}

 

That last bit is from Apple's sample. The counterpart is here:

 

- (void)viewDidLoad
{
[super viewDidLoad];

...

// Restore search term
if ([self savedSearchTerm])
{
[[[self searchDisplayController] searchBar] setText:[self savedSearchTerm]];
}
}

 

Saving/restoring the search criteria, nothing fancy. Then we get to the search routine itself:

 

- (void)handleSearchForTerm:(NSString *)searchTerm
{
[self setSavedSearchTerm:searchTerm];

if ([self searchResults] == nil)
{
NSMutableArray *array = [[NSMutableArray alloc] init];
[self setSearchResults:array];
[array release], array = nil;
}

[[self searchResults] removeAllObjects];

if ([[self savedSearchTerm] length] != 0)
{
for (NSString *currentString in [self contentsList])
{
if ([currentString rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location != NSNotFound)
{
[[self searchResults] addObject:currentString];
}
}
}
}

 

First we store the search term. Then we lazily create the searchResults array if needed. Next we clear out any previous search results. Then we loop through our main data, find any matching items, and add them to the searchResults array.

 

This method could vary greatly depending on what kind of data you are working with, and how it is arranged. This particular implementation is based on an example in the Mark/LaMarche book.

 

Now we get to the fun part: the table datasource and delegate methods. We've discussed a bit already about the need to have 2 separate data lists, and pointed out that we will be dealing with 2 separate tables. However, we only have one set of delegate methods here in the controller. We could use a completely separate object, as mentioned in the previous post, but that's not really necessary. So, we need some way of determining which set of data to use. You might get away with using some kind of flag, say BOOL isCurrentlySearching or something along those lines. I have fought enough battles with the search display controller in attempting to do other tasks to know that this approach won't work. Thus, we'll go with the way Apple's sample shows, and that is to make decisions based on which table is asking for information. In hindsight, this is a really obvious approach, but I'm not always on the ball as quickly as I should be.

 

First, the number of rows:

 

- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
NSInteger rows;

if (tableView == [[self searchDisplayController] searchResultsTableView])
rows = [[self searchResults] count];
else
rows = [[self contentsList] count];

return rows;
}

 

The important thing to realize here is that all of these table view delegate methods include the calling table view itself as a parameter. This allows you the means to identify which table is making the request. If you had a reason to design a view with multiple tables, this is exactly what you would do. If the table asking for info is the search table, we provide an answer based on the search list, otherwise we use our main list.

 

We do the exact same thing when providing a cell:

- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger row = [indexPath row];
NSString *contentForThisRow = nil;

if (tableView == [[self searchDisplayController] searchResultsTableView])
contentForThisRow = [[self searchResults] objectAtIndex:row];
else
contentForThisRow = [[self contentsList] objectAtIndex:row];

static NSString *CellIdentifier = @"CellIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

[[cell textLabel] setText:contentForThisRow];

return cell;
}

 

Constructing the cell itself doesn't need to change just because we're using a search table. The key thing is to make sure we're grabbing the right piece of information to populate that cell. "Green" might be at row 4 in our main list, but it could be at row 2 in the search results. Once again, we make a decision based on which table is asking, and grab data from the appropriate list.

 

I'm not really going into cell selection yet, but you would need to do something similar in tableView:didSelectRowAtIndexPath:. The index path can, and most likely will, be different depending on which table is being shown.

 

At last, we reach the part that makes this all work. We've been dealing with table delegate methods up to this point, but the search controller has delegate methods of its own. So we'll utilize a couple of those to make the actual search happen. First, to begin the search:

 

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller 
shouldReloadTableForSearchString:(NSString *)searchString
{
[self handleSearchForTerm:searchString];

return YES;
}

 

And that's it. The documentation notes this is an optional method, and NOT implementing it will cause the search table to reload as the search term changes. So the only reason we're doing this is to define what logic should be performed in response to the search string. And this next part is also optional, but if you want to do any cleanup after the search, this is where you could do it:

 

- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
[self setSavedSearchTerm:nil];

[[self mainTableView] reloadData];
}

 

We no longer need the search term to be saved, so get rid of it. And maybe it is appropriate to refresh the main table view.

 

That's pretty much all there is to it at a basic level. Obviously this is a simple app so far, but the search display controller handles a lot duties on its own. Here is the sample project for everything so far:

 

TableViewTutorial_Part2.zip

UITableView How-To: Part 1 - View Controller Setup

Part 2 | Part 3 | Part 4 | Part 5 | Part 6

 

A while back, I was preparing for a semi-major restructuring of SlickShopper. My 1.0 had hard-coded sizes everywhere, but I wanted to support screen rotation, so something had to change. I was in the process of rebuilding things using Interface Builder when I made some key discoveries about UINavigationControllers (they have a toolbar property) and UITableViewControllers (they inherently support resizing due to rotation). I bailed on the IB stuff, and started over using table view controllers exclusively. Version 1.5 onward contains table view controllers exclusively. I patted myself on the back for so deftly having avoided IB.

 

Today, I'm long past my fear of IB, and I've mostly given up on pure table view controllers. I use IB as much as possible, and prefer to set everything up as a plain view controller. I enjoy the flexibility this provides. (Tip: Don't name your view controllers as SomethingTableViewController, because the 'Table' part becomes incorrect if you change your mind about implementation later) I encounter a number of people struggling with basic aspects of table views, so I'm going to pool together the techniques I've learned from books and Apple's sample programs.

 

This will be the first installment of several posts devoted to the creation of plain view controllers that feature a table view. Today I'm going to focus on basic setup of the view controller. Future installments will look at using IB-based table cells, how to implement a search bar, and any other useful things I think of along the way. Please feel free to post requests in the comments area. My intention is to be as step-by-step as necessary, but I will also attempt to include a sample project at the end of each post.

 

Initial Setup

 

I'm not really going to go into the various places this view controller could be used. Theoretically, it should be perfectly usable in a view-based app, a navigation-based app, tab-based app, etc. So, create a new project using whatever template you like. I'm going to use the navigation-based template, as I intend to show how to pass data to a sub-controller at some point in this series. But feel free to use whatever template you want, as the choice doesn't really impact what I'm going to do here.

 

After the project has been set up, create a new file.

 

 

Choose a UIViewController subclass, and hit the toggle to indicate that you want to use a XIB file.

 

 

I'm calling mine SampleViewController, you can call it whatever you want. The XIB checkbox is relatively new, so if you don't have it, simply create your own XIB file, and give it the same name. And then start downloading the newest version of Xcode.

 

We need to do work in all 3 files that were just created, but in order to avoid bouncing around I'm going to work in this order: .h -> .xib -> .m.

 

Prepare The Header

 

Your .h file should look like this:

 

#import <UIKit/UIKit.h>

@interface SampleViewController : UIViewController
{
}

@end

 

Since this is a plain view controller, we need to add some information to it in order to work with a table view. The parts that we are about to add are included for free with table view controllers, hence the appeal. But it is easy enough to add manually, so here we go.

 

First, we need to adopt a couple of protocols. Table views are designed to be generic, and rely on other objects to provide customization. For our immediate use, customization mostly refers to providing content, but it can also apply to appearance. The necessary protocols are UITableViewDataSource, and UITableViewDelegate. Data source, as the name implies, provides the content. The delegate pattern is used throughout Cocoa, and indicates that one object will be doing work on behalf of another object. There are two protocols because they serve different needs, and if desired they could be distinct objects. We are already in a class that is perfectly capable of doing the work, but if you had a reason to do so, you could certainly make two more external classes to accomplish the same thing. For simplicity, generally speaking you'll just use your view controller. To indicate that your view controller can serve in these roles, add this to the .h file:

 

#import <UIKit/UIKit.h>

@interface SampleViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
{
}

@end

 

There are no required methods in UITableViewDelegate, but there are in UITableViewDataSource. So, if you build your project before we finish up, you will get some warning messages related to the absence of those required methods. You can ignore the warnings for now, but by the time we finish up, make sure the warnings are gone.

 

We are going to graphically place a table view into our main view in Interface Builder, just as if we were placing a button or a label. We will have a reason to talk to that table view object. The way to establish that line of communication is to declare IBOutlets here in the .h file. We need to declare a table view property, like this:

 

#import <UIKit/UIKit.h>

@interface SampleViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
{
}

@property (nonatomic, retain) IBOutlet UITableView *mainTableView;

@end

 

We're basically done now, but before we move on, let's take care of the structure that will hold our contents. I'm just going to use an array for now, as arrays work quite well with the way table views expect to receive information.

 

#import 

@interface SampleViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
{
}

@property (nonatomic, retain) IBOutlet UITableView *mainTableView;
@property (nonatomic, retain) NSMutableArray *contentsList;

@end

 

Lay Out The Interface

 

Open up the XIB file. We want the view to be capable of supporting landscape, so we need to change the resizing masks. Select the view, then hit Cmd-3 to bring up the size inspector. Toggle the masks as shown here so that the view is fully flexible, and go ahead and make the height 480 for good measure.

 

 

If you are unable to make these changes, hit Cmd-1, turn off any simulated UI elements like the status bar, then come back and try again. (Disclosure: I only figured that out just now while typing this up... I thought it was a bug. I've been deleting and re-creating the view for quite some time)

 

Drag a table view from the palette onto the view. It should automatically expand to fill the entire view.

 

 

The resizing masks should already be set, but go ahead and verify them for the table view just in case.

 

 

In order to talk to the table view, we need to use the IBOutlet that we declared in the .h. To do that, Right-click (Ctrl-click) on File's Owner, and drag to the table view. (I've resized the view for sake of screen capture here)

 

 

You should see the table view highlight, and you should see "Table View" appear in a little box at the lower right, thus confirming your selection. When you let go, a window will appear:

 

 

Select the name of the IBOutlet that was created in the .h file.

 

We're not quite done yet. Remember the data source and delegate from the .h file? That declaration simply published the fact that our view controller is willing to serve that role. But that alone does not mean that the table view knows who to talk to. There could be any number of conforming classes eligible, so we need to identify specifically which class(es) this table view will use.

 

Select the table view, and hit Cmd-2. At the top of the inspector are outlets for the delegate and dataSource. Select the circle next to each one, and drag to File's Owner (regular left-click drag).

 

 

 

So, the view controller is able to talk to the table view, the table view will request information from the view controller, and the whole thing is resizable. Thus concludes our trip to IB.

 

Implement

 

Now for the hard part. Most of what we will be doing in the .m file would be exactly the same or very similar if we were using a table view controller instead. Let's start at the top and work our way down.

First, synthesize the properties:

 

#import "SampleViewController.h"

@implementation SampleViewController

@synthesize mainTableView = ivMainTableView;
@synthesize contentsList = ivContentsList;

 

Most examples show dealloc at the bottom, but I prefer to have it up top so I can quickly glance at the properties. Follow memory management rules and release the properties.

 

- (void)dealloc
{
   NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

   [self setMainTableView:nil];
   [self setContentsList:nil];

   [super dealloc];

   NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

 

Somewhere we need to build the data that will appear in the table view. For a simple case like this, viewDidLoad will work just fine.

 

- (void)viewDidLoad
{
   NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

   [super viewDidLoad];

   NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"Red", @"Blue", @"Green", @"Black", @"Purple", nil];
   [self setContentsList:array];
   [array release], array = nil;

   NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

 

Build an array, stick it into the property, then release it.

 

For this example, we aren't too worried about the displayed contents being incorrect. But in a real app, if activity in another view controller could cause the contents here to change, we want to make sure that the user sees the updated information. To make the table refresh every time the view is displayed, we'll use viewWillAppear.

 

- (void)viewWillAppear:(BOOL)animated
{
   NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

   [super viewWillAppear:animated];

   [[self mainTableView] reloadData];

   NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

 

I mentioned before that UITableViewDataSource has some required methods, so let's get those out of the way. First, the table is going to ask the data source how many rows are involved. The answer should be based on our array, and we use this method to respond to the table's question:

 

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
   NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

   NSInteger rows = [[self contentsList] count];

   NSLog(@"rows is: %d", rows);
   NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
   return rows;
}

 

Note the section variable that we aren't using here. So far, we only have one section, so there isn't a need to worry about it. In a future post, I'll show how to do a multi-section table, at which point this method gets a bit more involved.

 

Next, the table is going to ask for a view to display in each row. Apple has provided a UIView subclass called UITableViewCell that is pre-configured for many common table needs. You create a cell, give it some content, and then give that cell to the table. Repeat as needed for each row. A lot of explanation is going to be needed here, so let's jump to the end result, and I'll discuss afterwards...

 

- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

   NSString *contentForThisRow = [[self contentsList] objectAtIndex:[indexPath row]];

   static NSString *CellIdentifier = @"CellIdentifier";

   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
   if (cell == nil)
   {
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
      // Do anything that should be the same on EACH cell here. Add subviews, fonts, colors, etc.
   }

   // Do anything that COULD be different on each cell here. Text, images, etc.
   [[cell textLabel] setText:contentForThisRow];

   NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
   return cell;
}

 

In summary:

  • Grab the object that has (or in this case, is) the information we want to display for this row
  • Ask the table view if any cells are available for recycling.
  • If not, create a new cell
  • Specify the content for the cell

I'll talk more about cell customization at a later date, but for now please note the comments I added regarding where you should customize different elements of the cell.

First, a little bit about the NSIndexPath. If you were trying to describe the location of a point on a grid, you would most likely use (X,Y) coordinates. The index path provides a way of describing a location within the table, but instead of (X,Y) coordinates, it is using (section, row) coordinates. These are numbered in the exact same way an array is, so the first item is 0, the second item is 1, and so on. We only have one section, so we will only be dealing with section 0 for now. Within our only section, we are providing five pieces of information, so we'll be talking about row 0, row 1,....up to row 4.

 

So this method begins with the table asking the question "Hey, I'm now at the first section and the second row... what should I show here?" We need to figure out which row is being requested, and we do that by asking the indexPath for its row value. [indexPath row] (later we'll do the same thing to get a section value). Assuming we are building the table up from scratch, we should be dealing with the first row, so row 0. Now I know which piece of information I want from the array: the first item, so the item at index 0. For convenience I assign that to a local variable.

Next I declare a string variable. I don't actually know what "static" technically means, other than the obviously implied "this does not change". I suppose you could #define a constant instead. The purpose of this string will be to allow the table view to identify cells in a queue that it will create.

 

The table's cell queue exists because flinging your way through a list of data needs to happen as fast as possible, but building a cell from scratch can be expensive from a performance standpoint. If we were providing 1000 strings for this table, we don't want to actually create 1000 cells. We only need to create enough to cover the visible screen, plus a couple extra for buffer, and then we can reuse those cells over and over again. As a cell slides off the top of the screen, it goes into the queue, only to reappear at the bottom of the screen with new content. We don't want to build new cells if it can be avoided.

Thus, the next thing we do is ask the table if any cells are available for reuse, here:

 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

 

We use the string identifier, because there could be multiple kinds of cells being stored, so we want to make sure we get the right kind. If a cell is available, it will be provided to the cell variable. However, if there aren't any cells available (as would be the case when starting from scratch), the return from this call is nil. So, we find out if we actually have a cell right now:

 

if (cell == nil)
{
   cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
   // Do anything that should be the same on EACH cell here. Fonts, colors, etc.
}

 

If there is a cell, this part doesn't happen. If there isn't a cell, this part will build a new one.

Lastly, we provide our content:

 

// Do anything that COULD be different on each cell here.  Text, images, etc.
[[cell textLabel] setText:contentForThisRow];

 

Standard cells have a label property, and I'm setting the text using our content string. I'm going to again emphasize the comments I've put in there. When you get to this point of the method, you have 2 possibilities: 1) The cell is brand new, or 2) The cell has been recycled. Recycled cells will most likely still have their old content, so you cannot make assumptions about the state of the cell you are working with. It could be pristine, it could be dirty. So this area of the method MUST make sure the end result is correct. If you alternate font colors between red and green, then you should have an if/else statement here that makes the font red OR makes the font green. You cannot assuming the incoming color is correct.

 

That covers the required methods for the data source. There are many, many other optional methods - from dataSource and from delegate - for performing a variety of tasks, but for now I just want to draw attention to one of them.

 

If you build-and-run your app, you should see the list of colors in your table. If you tap a row, it will stay highlighted. Let's turn that off. This method is how the table says "Hey, I was touched here... what do you want me to do about it?"

 

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

   [tableView deselectRowAtIndexPath:indexPath animated:YES];

   NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

 

We will do a lot more with this method later, but for now we'll simply deselect the row.

And thus concludes this edition of table talk. Tune in, uh... later... for the next installment. In the meantime, here is the sample project for this stage of the exercise.

TableViewTutorial_Part1.zip

Tuesday, July 26, 2011

New Web Site!

After many, many... many months of neglect, we at last have a new web site!  Our thanks go to Xponential Site Design for the fantastic graphic design, as well as the implementation of everything you see here.