I’m using the following code to just make a single UILabel on my cell. (I know this example is contrived; I can’t even get this to work much less my ultimate design goal.)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Photo";
UILabel *username;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
username = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 120.0, 20.0)];
username.tag = USERNAME_TAG;
username.font = [UIFont systemFontOfSize:14.0];
username.textAlignment = UITextAlignmentLeft;
username.textColor = [UIColor blackColor];
username.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:username];
} else {
username = (UILabel *)[cell.contentView viewWithTag:USERNAME_TAG];
}
//NSDictionary *photos = [self.photos objectAtIndex:indexPath.row];
username.text = @"Testing!";
return cell;
}
I got this template code from here
However, when I run the code, there is no text label in the cell, but the accessory does show up.
Apple changed the behavior of
dequeueReusableCellWithIdentifierwhen they released 5.0.In 5.0+ it is guaranteed to always return a copy of your cell (if it exists in your xib/storyboard), even if you haven’t even loaded a cell yet. Prior to this, it would return a cell only if there was one that was ready to be recycled.
Because of this, some older code which assumes that you will receive nil unless you have already initialized it will break.
So, get rid of the identifier (or the entire cell) in your xib/storyboard or modify your logic so that it initializes it when needed (perhaps based on whether or not there is a view with the specified tag).