UITableView imageView显示滚动后图像不应出现的图像



我有一个uitableview,里面有一个人员列表。有些记录有图像,有些记录没有。如果我向下滚动列表,它看起来是正确的,但如果我向上滚动,则另一个人的图像开始显示在其他人的单元格行上,而该行不应该显示图像

// START CELL LABELLING FOR  TABLE VIEW LIST //
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    Person *person = [arrayOfPersons objectAtIndex:indexPath.row];

    NSString *personPhoto = person.personPhoto;
    NSString* imgPath = [docPath stringByAppendingPathComponent:
                      [NSString stringWithFormat:@"%@", personPhoto] ];

    if ([[NSFileManager defaultManager] fileExistsAtPath:imgPath]){
        NSLog(@"FILE EXISTS");
    imageView = [[UIImageView alloc] initWithFrame:CGRectMake(240, 0, 67, 67)];
    imageView.image = [UIImage imageWithContentsOfFile:imgPath];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [cell.contentView addSubview:imageView];
    }else{
        NSLog(@"Does Not Exist");
    }

    cell.textLabel.text = person.personName;

    return cell;
    imageView = nil;
    personPhoto = @"";
    imgPath = @"";
}
// END CELL LABELLING FOR TABLE VIEW LIST //

发生这种情况的原因是表单元格被重复使用。

使用[tableView dequeueReusableCellWithIdentifier:CellIdentifier]时,将返回一个已显示在表视图中的单元格(用于不同的索引路径)。您可能已经在上一个索引路径中为Person向该单元格添加了图像视图,但无法删除此图像。

因此,当当前人物没有照片时,先前的图像将在单元格中保持可见。

我建议您创建自己的UITableViewCell子类,并向其添加UIImageView,这样您就可以轻松地获得对图像视图的引用(如果您愿意,也可以使用视图标记)。

无论哪种方式,当用户没有照片时,您都需要删除图像视图/将图像设置为nil

最新更新