How to Create a Custom Cell for a UITableView

I find myself doing this a lot with this new iPhone app that I’m working on so I wrote up the steps for future reference.

1. Create a subclass of UITableViewCell.

2. In the UITableViewCell subclass header (.h) file:

– Add IBOutlet properties for your custom cell components.

IBOutlet UILabel *jobCardLabel;
IBOutlet UILabel *jobCardDesc;

– Add @property statements for each of the IBOutlet properties

@property (nonatomic, retain) IBOutlet UILabel *jobCardLabel;
@property (nonatomic, retain) IBOutlet UILabel *jobCardDesc;

3. In the UITableViewCell subclass main (.m) file add @synthesize statements for the IBOutlet properties.

@synthesize jobCardLabel;
@synthesize jobCardDesc;

4. Create a Nib file from the Empty  Xib template. Open this Nib file in Interface Builder.

5. In Interface Builder:

– Add a TableViewCell to the Nib file.

– Add controls to the TableViewCell that correspond to the IBOutlet properties you created in the UITableViewCell subclass file.

– In the Identity Inspector, set the Class to the UITableViewCell subclass.

– In the Attributes Inspector, set the Identifier to an appropriate value.

– In the Connections Inspector, Ctrl-Drag from each IBOutlet to the corresponding control in the TableViewCell.

6. Add code to the cellForRowAtIndexPath method in the parent ViewController main (.m) file (underlined items need to be replaced with actual values).

static NSString *CellIdentifier = @"Cell_Identifier_Text");
UITableViewCell_subclass *cell = (UITableViewCell_subclass *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *nib = [NSBundle mainBundle] loadNibNamed:@"Name_of_Nib" owner:self options:nil];
for (id oneObject in nib)
if ([oneObject isKindOfClass:[UITableViewCell_subclass class]])
cell = (UITableViewCell_subclass *)oneObject;
}
// Set cell control contents

7. Add an #import statement for the UITableViewCell subclass header file to the parent ViewController main file (underlined items need to be replaced with actual values).

#import "UITableViewCell_subclass.h"
This entry was posted in Software Development and tagged . Bookmark the permalink.