我创建了一个多选列表,允许选择多种成分。UITableViewCell重用:单元格显示不正确 - 没有按预期重用
在我的tableview中,可以根据成分的列表属性启用或禁用单元格。如果成分的列表属性已设置,则单元格将被禁用。
但是,当一个单元格被重新使用时,它不会像我期望的那样显示。下面的图片比我能更有效地解释问题。
(不应该被使能的成分有:锦上添花,炼乳和Cournflour。)
第一个图像显示禁止,如预期注释的三种成分。
但是,在第二张图片中,向下滚动显示某些成分被禁用(但您可以选择它们,并且它们具有完全的相互作用)。
第三张图片显示滚动回顶部之后的列表。某些成分已经变灰,并注意Cornflour如何显示为启用,即使您无法进行交互/选择。
问题是关于细胞再利用。看起来单元格在重用时没有被“重置”,因此保留了一些“旧”的外观。
以下是cellForRowAtIndexPath:
的代码,因为我确定这是问题所在(尽管我看不出有什么问题)。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Fetches the corresponding Ingredient from the ingredientArray
Ingredient *ingredient = [self.ingredientArray objectAtIndex:indexPath.row];
if ([ingredient.list isEqualToString:@"Lardr"])
{
cell.userInteractionEnabled = NO;
cell.detailTextLabel.text = @" Already in your Lardr";
}
else if ([ingredient.list isEqualToString:@"Shopping List"])
{
cell.userInteractionEnabled = NO;
cell.detailTextLabel.text = @" Already on your Shopping List";
}
else
{
cell.userInteractionEnabled = YES;
cell.detailTextLabel.text = @"";
}
// Add a checkmark accessory to the cell if the ingredient is on the selectedIngredients array
if ([self.selectedIngredients containsObject:ingredient])
cell.accessoryType = UITableViewCellAccessoryCheckmark;
else
cell.accessoryType = UITableViewCellAccessoryNone;
cell.textLabel.text = ingredient.name;
return cell;
}
我在我束手无策试图弄清楚这一点,和我读过这一切都让甚至远程相关的问题,但都无济于事。有什么问题?!
我的逻辑是,每个单元中,为textLabel,detailTextLabel,userInteractionEnabled和accessoryType属性设置,无论它通过if语句,所以我不能看到执行路径为什么即使再利用之后,单元格显示不正确。
编辑:在试图找出问题的根源,我已经试过“重置”细胞回到它通过添加默认以下右其取出相应的成分线之上:但无济于事。
cell.userInteractionEnabled = YES;
cell.textLabel.text = nil;
cell.detailTextLabel.text = nil;
cell.accessoryType = UITableViewAccessoryNone;
但是,什么是有趣的,完全不合逻辑 - 当我提出以下行cell.textLabel.text = ingredient.name
直接下读取Ingredient *ingredient = [self.ingredientArray objectAtIndex:indexPath.row];
,绝对没有的造型适用于任何细胞,即使用户交互设置下面进一步行(并按预期禁用相关单元)。
我在想,单元格属性的设置顺序是否重要?我知道它不应该,但外观会根据上述情况而改变。
更新:我已经解决了这个问题;请参阅下面的答案。
你在使用StoryBoards吗? –
什么是文字灰色? –
您发布的代码没有任何问题。将用户交互设置为NO不会使文本变灰。我认为你的问题可能在于你用什么方法来做到这一点。 – rdelmar