Skip to content

Instantly share code, notes, and snippets.

@andrewsardone
Created February 14, 2012 15:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewsardone/1827605 to your computer and use it in GitHub Desktop.
Save andrewsardone/1827605 to your computer and use it in GitHub Desktop.
Creating a custom UITableViewCell

Apple's Documentation

Option 1: Programmatic Setup and Subview Manipulation

No UITableViewCell subclass

Add subviews to a cell's contentView, or tweak properties of a certain cell style's subviews.

Example:

#define COOL_LABEL_TAG 1
#define COOL_PHOTO_TAG 2

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UILabel *coolLabel;
    UIImageView *coolPhoto;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

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

        // add custom content for newly initialized cells
        coolLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 220.0, 15.0)] autorelease];
        coolLabel.tag = COOL_LABEL_TAG;
        // customize coolLabel
        [cell.contentView addSubview:coolLabel];

        coolPhoto = [[[UIImageView alloc] initWithFrame:CGRectMake(225.0, 0.0, 80.0, 45.0)] autorelease];
        coolPhoto.tag = COOL_PHOTO_TAG;
        // customize coolCoolPhoto
        [cell.contentView addSubview:coolPhoto];
    } else {
        // for reusable cells, retrieve pointers to the custom content
        coolLabel = (UILabel *)[cell.contentView viewWithTag:COOL_LABEL_TAG];
        photo = (UIImageView *)[cell.contentView viewWithTag:COOL_PHOTO_TAG];
    }

    // configure cell and its custom content

    return cell;
}

UITableViewCell subclass

Option 2: Custom table view cells via Nib files

Subclass UITableViewCell, creating an instance with the appropriate UITableViewCellStyle. Then override -layoutSubviews to reposition default content, style default content, and/or add additional content views.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment