Custom UITableViewCell

There is more that one way to do this. For my purposes I wanted to lay out the block of labels in Interface Builder and have a custom view that linked the cell to the object it was going to display data from.

  • Create a class for the view derived from UITableViewCell
  • Add members for the controls you want
  • Add an empty nib file to the project (create it in Interface Builder)
  • Add a table view cell to the nib
  • Change the class of the table view cell to the derived class
  • set the resourceIdentifier for the cell in the Identifier field in the interface builder properties
  • Add the controls you need to the cell container
  • Link the controls in Interface Builder to the outlets in your custom view

Now in the

- (UITableViewCell * ) tableView: (UITableView * )tv
           cellForRowAtIndexPath: (NSIndexPath *) path

message use the following code to load your custom cell when required:

tvc = [tv dequeueReusableCellWithIdentifier:customCellView];
if ( ! tvc)
{
  NSArray *objects = [[NSBundle mainBundle] loadNibNamed:nibName
                                                   owner:nil
                                                 options:nil];
  //you could just assume objectAtIndex: 0 was the item you want....
  //but this is safer
  for(id item in objects)
  {
    if ( [item isKindOfClass:[UITableViewCell class]])
    {
	tvc = (CustomViewClass *)item;
	break;
    }
  }
}

Where tvc is the UITableViewCell pointer you want to return

customCellView is the identifier you set in interface builder

nibName is the nib file you created

CustomViewClass is the custom view you created

Leave a Reply

Your email address will not be published. Required fields are marked *