【发布时间】:2011-09-11 06:51:06
【问题描述】:
我正在尝试使用两种不同类型的 UITableViewCell 打印 UITableView。
- 空的表格视图单元格不包含任何内容(前 2 个单元格),只有黑色背景
- 表格视图单元格包含从 1 开始的标签、图像等(第 3 个和后续单元格)
我的表格视图的高度可以随时容纳至少 3 个表格视图单元格。
当我第一次加载表格视图时,表格视图看起来非常好 - 第一两行是黑色的,接下来是第三行,其标签上写着“1”。
但是,在向下滚动到底部后又向上滚动。我的前两个空单元格(应该是空的)充满了只能在第三个和后续单元格中找到的东西。
我怀疑这种行为来自重复使用单元格的表格视图,但我仍然无法弄清楚。
代码sn-ps:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
switch ([indexPath row]) {
case 0:
cell.contentView.backgroundColor = [UIColor blackColor];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
break;
case 1:
cell.contentView.backgroundColor = [UIColor blackColor];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
break;
default:
cell.contentView.backgroundColor = [UIColor blackColor];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
UILabel *rowLabel = [[UILabel alloc] initWithFrame:CGRectMake(25, 30, 200, 30)];
rowLabel.text = [NSString stringWithFormat:@"Row %d", [indexPath row]-1];
rowLabel.backgroundColor = [UIColor blackColor];
rowLabel.textColor = [UIColor whiteColor];
[rowLabel setFont:[UIFont fontWithName:@"GillSans-Bold" size:18]];
[cell.contentView rowLabel]; [rowLabel release];
UIButton *aButton = [[UIButton alloc] initWithFrame:CGRectMake(100, 50, 40, 40)];
[aButton setImage:anImage forState:UIControlStateNormal];
[cell.contentView addSubview:aButton];
[aButton release];
break;
}
return cell;
}
【问题讨论】:
-
我可能已经找到了我的解决方案。我接受了使用唯一重用标识符的建议。我对每个细胞都这样做了。而且,我将开关盒移到了 if 中。当 stackoverflow 允许时,我会发布我的答案!
-
这不是正确的解决方案,您应该尽可能重复使用单元格,否则您的滚动可能会很慢。
-
@jrturton,感谢您告诉我!当您说重用时,您的意思是重用单元格内的每一件事(包括按钮、图像)吗?
-
我已经更新了我的答案,这是你应该做的事情。
标签: iphone ios ipad uitableview