Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.