kwigbo

Adventures in iOS!

1 note &

Custom UITableViewCell Without Subclassing

I was going to do another game dev post today, but because of a lack of time I will be doing a short tutorial on customizing a UITableViewCell without subclassing.

I find myself in a position frequently where I want to add a label or image to a table cell. You can easily subclass UITableViewCell and add as many other components as you want. I don’t like this solution for adding just a few component due to the fact that it adds two files to my project. Since I like to keep the number of files in my project to a minimum, this is less than ideal.

What we are going to do is tag the sub components we want in our table cell. At the top of the .m for the UITableViewDataSource I define a constant…

#define LABEL_TAG 1

In the cellForRowAtIndexPath method when the cell is created we can simply create a label component and set its tag. A UIView tag property will default to zero so we just have to set the tag to greater than zero.

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{		
	UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:@"MyCell"];
	
	if(!cell)
	{
		//Create the cell
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"MyCell"] autorelease];

		//Create the label
		UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, aTableView.frame.size.width, 40)];
		//Tag the label
		label.tag = LABEL_TAG;
		//Add the label to the cell
		[cell.contentView addSubview:label];
		[label release];
	}

	// Get the label for the current cell
	UILabel *header = (UILabel *)[cell viewWithTag:LABEL_TAG];
	// Set the label text
	header.text = currSet.setName;

	return cell;
}

This technique can be used to add any number of components to a UITableViewCell. However, I would only recommend this when the amount of components added is small.

Filed under tutorials

  1. kwigbo posted this