我的 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;
}
最佳答案
您需要确保 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/