iphone - 当表格滚动到 View 之外时 UITableViewCell 的奇怪行为

标签 iphone objective-c cocoa-touch

我有一个扩展 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/

相关文章:

iphone - NSDate 独立于时区?

objective-c - 我们可以使用 iPhone 应用程序中的任何 Wordpress 插件获取数据(或将数据插入数据库)吗

objective-c - 通过 Cocoa 中的 NSURLRequest/NSURLConnection 接收 HTTP header

ios - UIImagePickerController 和 ALAssetsLibrary 的用例

ios - SpriteKit 中的无限滚动背景

ios - 根据 Text 动态获取 UILabel 的高度返回不同的 iOS 7.0 和 iOS 6.1 值

iphone - 连续调用 startRecordingToOutputFileURL :

ios - 难以访问另一个类的属性

ios - 有没有办法让用户选择本地通知的声音?

ios - 右对齐 UISearchbar 占位符