如果语句在tableView中显示奇怪的结果

用户名

在我的cellForRowAtIndexPath方法中,我使用以下if语句:

if ([taskitem.isCritical isEqualToString:@"iscritical"]){
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.backgroundColor = [UIColor redColor];
}
else if ([taskitem.isUrgent isEqualToString:@"isurgent"]){
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.backgroundColor = [UIColor blueColor];
}
else if ([taskitem.isCompletedOK isEqualToString:@"iscompleted"]){
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.backgroundColor = [UIColor greenColor];

    UIButton *doneButton4 = [[UIButton alloc]initWithFrame:CGRectMake(0, 10, 12, 12)];
    [doneButton4 setImage:[UIImage imageNamed:@"done"]forState:UIControlStateNormal];
    [cell addSubview:doneButton4];
}
else {
       cell.textLabel.textColor = [UIColor blackColor];
   }
    cell.textLabel.text = taskitem.taskName;

问题是,if statements如果用户点击任何节标题,它们将改变其行为。

您是否在代码中发现任何可能是这种奇怪行为的原因的错误,还是应该在另一种方法中寻找其他原因?

戴夫·伍德

看来您可能遇到了单元重用问题。您需要确保在每种情况下(或撤消)在每种情况下都可以完成任何操作。

例如,在您的三个条件中,首先设置文本颜色和背景颜色。但是在第四种情况下(其他情况),您仅设置了文本颜色,而背景色则保持为上次使用该单元格时的背景色。您还需要在其他情况下设置背景颜色。(或者,您可以在if之前将所有项目设置回默认值)。

在第三种情况下,这里有第二个问题,它会创建一个按钮并将其添加到单元格。但是在其他情况下,请勿删除该按钮(如果存在)。因此,当您较早获得用于完成商品的单元格时,您将得到一个不属于该按钮的按钮。即使该单元格用于另一个完成的项目,您也将在同一单元格上获得两个按钮。一个在另一个之上(因此它可能不可见,但这仍然是一个问题)。

尝试使用以下代码:

UIButton* oldButton = [cell viewWithTag:253];
if (oldButton)
{
    [oldButton removeFromSuperview];
}

if ([taskitem.isCritical isEqualToString:@"iscritical"]) {
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.backgroundColor = [UIColor redColor];
}
else if ([taskitem.isUrgent isEqualToString:@"isurgent"]) {
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.backgroundColor = [UIColor blueColor];
}
else if ([taskitem.isCompletedOK isEqualToString:@"iscompleted"]) {
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.backgroundColor = [UIColor greenColor];

    UIButton *doneButton4 = [[UIButton alloc] initWithFrame:CGRectMake(0, 10, 12, 12)];
    [doneButton4 setImage:[UIImage imageNamed:@"done"] forState:UIControlStateNormal];
    doneButton4.tag = 253;
    [cell addSubview:doneButton4];
}
else {
    cell.textLabel.textColor = [UIColor blackColor];
    cell.textLabel.backgroundColor = [UIColor whiteColor];
}

cell.textLabel.text = taskitem.taskName;

我不建议在生产代码中使用这样的标签,但这是查看它是否可以解决您的问题的快速方法。在实际代码中,将UITableViewCell子类与带有done属性的属性一起使用,即可显示和隐藏。理想情况下,您不必每次都创建它,因为这是一项昂贵的操作,并且可能会降低滚动性能。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章