ios - UIImageView 添加到单元格 contentView 在滚动 UITableView 时随机显示

标签 ios objective-c

我的 UITableView 正在从数组中提取数据。此数组中的项目具有名为 IsSelected 的属性。我正在尝试将一个 UIImageView 放在单元格 contentView 中,用于每个选定的项目。

UITableView 但是,当重用单元格时,我的图像会在本不应重用的单元格上重用。我无法弄清楚我应该如何以不同的方式做这件事。我附上了显示问题的屏幕截图。如果我继续上下滚动,图像就会到处都是:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *SchoolCellIdentifer = @"SchoolCellIdentifier";

    SchoolInfoItem *item = [self.schoolsArray objectAtIndex:indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SchoolCellIdentifer];

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SchoolCellIdentifer];
        cell.contentView.backgroundColor = [BVColors WebDarkBlue];
    }

    cell.textLabel.text = item.Name;

    if ([item.selected isEqualToString:@"1"])
    {
        cell.contentView.backgroundColor = [BVColors WebBlue];
        UIImageView *selectedItemCheckMarkIcon = [[UIImageView alloc] initWithFrame:CGRectMake(300, 13, 17, 17.5)];
        [selectedItemCheckMarkIcon setImage:[UIImage imageNamed:@"check-mark.png"]];
        [cell.contentView addSubview:selectedItemCheckMarkIcon];
    }
    else
    {
        cell.contentView.backgroundColor = [BVColors WebDarkBlue];
    }

    return cell;
}

enter image description here

最佳答案

您需要确保 UIImageView 已从单元格内容 View 中移除。在您的代码中,当单元格出列时,imageview 似乎仍在单元格 View 层次结构中。

最好的解决方案是让您的单元格保留对 ImageView 的引用,并在必要时将其删除。

采取以下措施:

if ([item.selected isEqualToString:@"1"])
{
    cell.contentView.backgroundColor = [BVColors WebBlue];
    cell.myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(300, 13, 17, 17.5)];
    [selectedItemCheckMarkIcon setImage:[UIImage imageNamed:@"check-mark.png"]];
    [cell.contentView addSubview:cell.myImageView];
}
else
{
    [cell.myImageView removeFromSuperview];
    cell.myImageView = nil;
    cell.contentView.backgroundColor = [BVColors WebDarkBlue];
}

请注意在其他情况下移除 ImageView 。

关于ios - UIImageView 添加到单元格 contentView 在滚动 UITableView 时随机显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17222994/

相关文章:

ios - 是否可以自动化涉及 iOS 应用程序双因素身份验证的测试?

ios - 状态恢复工作但随后在 viewDidLoad 中无效

iphone - 即使 removedOnCompletion = FALSE,CABasicAnimation 也会跳回;和 fillMode = kCAFillModeForwards;

iphone 开发 : how to auto facebook login if the facebook app already logged in

ios - 在 iPad 上模拟 sleep 模式

ios - 由于内存原因,App在iPad 1和iPad 2上崩溃的原因更多:为什么?

ios - 向上滚动时折叠 View (iOS)

ios - UISearchBar 属性

ios - 静音时播放iOS声音

ios - 将可重用的自定义 UIView 添加到多个 UIViewController