我正在创建自定义表格视图单元格,但结果不正确。 我的代码:
- (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;
}
结果: 这是截图,当uitableview加载时:
但如果此单元格变为不可见,并且在可见结果不好之后:
我的错误在哪里?
答案 0 :(得分:2)
您正在重复使用单元格,因此他们添加了img和titleLabel。您正在同一单元格上添加更多子视图。 您可以在添加新单元格之前删除重用单元格中的titleLabel和img。为此,您可以在两个视图上设置标记值。例如,您可以写:
titleLabel.tag = 0xff ;
和
img.tag = 0xfe ;
然后,当您重复使用单元格时:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
} else {
[[cell viewWithTag:0xff] removeFromSuperview];
[[cell viewWithTag:0xfe] removeFromSuperview];
}