当表滚动出视图时,UITableViewCell奇怪的行为

Coo*_*coa 2 iphone cocoa-touch objective-c

我有一个扩展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;
}    
Run Code Online (Sandbox Code Playgroud)

And*_*ant 5

出于内存原因,UITableView在滚动时重用单元格(例如dequeueReusableCellWithIdentifier)调用.

这意味着您收到的单元格无论如何都可以配置为与该标识符一起使用,因此您必须重置所有这些属性.

在你的情况下,我怀疑你被给了一个隐藏图像的单元格,所以这将解决它:

  NSDictionary *serverData = myData // previously defined.
  if ([[serverData valueForKey:@"foo"] isEqualToString:@"0"]) 
    cell.myImage.hidden = YES;
  else
    cell.myImage.hidden = NO;
Run Code Online (Sandbox Code Playgroud)