我有一个扩展 UITableViewCell 的类。出于本练习的目的,我们将其称为“CustomCell”。在 CustomCell 中,我有一个 UIImageView IBOutlet 设置。本例中的图像实例名称是 myImage。我希望根据从服务器返回的某些标准来显示此图像。该数据是一个字典,在本练习中我们将其称为“serverData”。首先,UITableView 渲染得很好,UIImageView 出现在它应该出现的单元格中。当我开始滚动实际的 UITableView 时,就会出现问题,图像会丢失。不知何故,它没有被正确缓存或出列。不确定问题出在哪里或如何更好地改进这段代码。以下是摘录:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CustomCellIdentifier = @"CustomCellIdentifier";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell"
owner:self options:nil];
cell = (CustomCell *)[nib objectAtIndex:0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
NSDictionary *serverData = myData // previously defined.
if ([[serverData valueForKey:@"foo"] isEqualToString:@"0"])
cell.myImage.hidden = YES;
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
return cell;
}
最佳答案
由于内存原因,UITableView 在滚动时重用单元格(例如 dequeueReusableCellWithIdentifier)调用。
这意味着您收到的单元格可能已以与该标识符一起使用有效的任何方式进行配置,因此您必须重置所有这些属性。
就你的情况而言,我怀疑你得到的单元格中的图像已被隐藏,因此这将修复它:
NSDictionary *serverData = myData // previously defined.
if ([[serverData valueForKey:@"foo"] isEqualToString:@"0"])
cell.myImage.hidden = YES;
else
cell.myImage.hidden = NO;
关于iphone - 当表格滚动到 View 之外时 UITableViewCell 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/632053/