I’m creating custom table view cells, but result is incorrect.
My code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *currentComment = [comments objectAtIndex:indexPath.row];
static NSString *CellIdentifier = @"TitleCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
int commentLevel = [[currentComment objectForKey:@"level"] intValue];
NSString *commentText = [currentComment objectForKey:@"text"];
UILabel *titleLabel = [[UILabel alloc] init];
titleLabel.numberOfLines = 0;
[titleLabel setFont:[UIFont fontWithName:@"Verdana" size:17.0]];
titleLabel.lineBreakMode = UILineBreakModeWordWrap;
CGSize textSize;
if (commentLevel == 0) {
textSize = [commentText sizeWithFont:titleLabel.font constrainedToSize:CGSizeMake(310, FLT_MAX) lineBreakMode:UILineBreakModeWordWrap];
titleLabel.frame = CGRectMake(5, 5, textSize.width, textSize.height);
} else {
textSize = [commentText sizeWithFont:titleLabel.font constrainedToSize:CGSizeMake((305-10*commentLevel), FLT_MAX) lineBreakMode:UILineBreakModeWordWrap];
titleLabel.frame = CGRectMake(15 + 10*commentLevel, 5, textSize.width, textSize.height);
UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"06-arrow-northwest"]];
img.frame = CGRectMake(5, 5, 15, 15);
[cell.contentView addSubview:img];
}
titleLabel.text = commentText;
[cell.contentView addSubview:titleLabel];
return cell;
}
- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *currentComment = [comments objectAtIndex:indexPath.row];
int commentLevel = [[currentComment objectForKey:@"level"] intValue];
NSString *text = [currentComment objectForKey:@"text"];
CGSize size;
if (commentLevel == 0) {
size = [text sizeWithFont:[UIFont fontWithName:@"Verdana" size:17.0] constrainedToSize:CGSizeMake(310, FLT_MAX) lineBreakMode:UILineBreakModeWordWrap];
} else {
size = [text sizeWithFont:[UIFont fontWithName:@"Verdana" size:17.0] constrainedToSize:CGSizeMake((305-10*commentLevel), FLT_MAX) lineBreakMode:UILineBreakModeWordWrap];
}
float height = size.height;
height = height + 40;
return height;
}
Result:
It’s screenshot, when uitableview loaded:

but if this cell become invisible and after it visible result is bad:

Where is my mistake?
You are reusing cells, so they have the img and titleLabel added. You are adding more subviews on the same cell.
You can remove the titleLabel and img in the reused cell before adding the new ones. To do this, you can set tag values on both views. For example, you can write:
and
Then, when you reuse the cell: