- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell2";
UILabel *titleLabel;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, 300, 20)];
[cell.contentView addSubview:titleLabel];
titleLabel.tag = 0011;
}
else
{
titleLabel = (UILabel *)[cell.contentView viewWithTag:0011];
}
// Configure the cell...
NSMutableString *title = [NSMutableString stringWithString:@"Customer: "];
[title appendString:[titles objectAtIndex:indexPath.row]];
titleLabel.text = title.copy;
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textAlignment = UITextAlignmentLeft;
titleLabel.font = [UIFont systemFontOfSize:18.0];
My cell is never nil, and my titleLabel, because of that never got allocated, although my cells are generated. I can not see how this is possible. The if state is never true, which should be for the cells that are being generated for the first time, but my cells are created as they should be, without my titleLabel’s
It sounds as if you are using iOS 5 (or later) and Storyboards.
Under iOS 5 (or later), if you are using Storyboards and the TableView Controller, the
dequeueReusableCellWithIdentifier:method is guaranteed to return a cell (provided that you have defined a cell with the given identifier in the Storyboard).If this is the case, the solution is to fully create the custom table cell in the Storyboard. Go to your Table View in your Storyboard, select
Content:Dynamic Prototypesand make thePrototype Cells:1. Now layout your cell graphically to be exactly what you want. Now click on the cell and setIdentifier:Cell2. You will now not need to create the label at runtime or check if it is nil. Full details including how to reference the labels you have setup are in the iOS 5 Release Notes (link below) or in many tutorials on the web.See the iOS 5 Release Notes section Configuring Table Views