ios - UITableViewCell 重用单元格重复值

标签 ios objective-c uitableview

我在重用 UITableViewCell 时遇到了一个经典问题。我知道问题出在哪里,但我不知道我做错了什么或如何解决。当屏幕首次呈现时,一切看起来都很棒。但是当用户滚动时,相同的图像和文本会以 8 行为一组重复显示。

在该方法的末尾,我打印出应该显示的文本值。这个值看起来不错,indexPath.row 值也是如此。我只是无法正确地重复使用细胞。

我省略了图像刷新代码,因为它有点复杂而且与主要问题无关。请关注文本更新,我相信图像更新将遵循类似的模式。

我认为我正在正确设置单元格。每个 subview 仅添加到 cell==nil block 中。然后,我尝试更改此 block 之外的文本。但不知何故,它没有得到正确的指针引用???我卡住了。

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    MyObject *obj = [self.fetchedObjects objectAtIndex:indexPath.row];
    UILabel *name;
    UIImageView *imgView;

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

        name = [[UILabel alloc] init];
        name.frame = CGRectMake(40, 0.0, _tableView.frame.size.width-40, 44);
        name.adjustsFontSizeToFitWidth = YES;
        name.minimumScaleFactor = 0.5;
        [cell addSubview:name];

        imgView = [[UIImageView alloc] init];
        imgView.frame = CGRectMake(0, 4, 36, 36);
        imgView.image = [UIImage imageNamed:@"myimage.png"];
        [imgView setContentMode:UIViewContentModeScaleAspectFit];
        [cell addSubview:imgView];
    }

    // this has to be outside the `cell == nil` block, right???        
    name.text = obj.name;

    // this output is perfect - but the actual cells are repeated!
    NSLog(@"indexpath: %d", indexPath.row);
    NSLog(@"name from array: %@", obj.name);

    return cell;
}

最佳答案

如所写,对于重复使用的单元格,nameimgView 值将为 nil

您需要将 else 添加到您的 if 语句以通过访问现有 View 来设置 nameimgView来自细胞。

关于ios - UITableViewCell 重用单元格重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33840879/

相关文章:

ios - 首次注册该服务时,iOS 上的 IBM-Bluemix 推送服务使应用程序崩溃

ios - UITextField/UITextView/UISearchBar 上的死锁/硬卡住成为FirstResponder

iphone - UITableViewCell 编辑模式,如联系人应用

uitableview - 如何使 UITableViewCell 显示为禁用?

ios tableview 图像不释放内存

ios - 在 UITableViewCell 中检测具有灵活宽度的 View 的最终布局大小

ios - 当 App 从后台 iOS 启动时从特定场景开始

ios - iPhone无需代码即可更改后退按钮标题

iphone - 有没有一种方法可以在不必手动编写 setter 和 getter 的情况下对原子属性进行延迟初始化?

ios - 将 NSDictionary 添加到 NSMutableArray 后访问键。 iOS