选择单元格时更改单元格的颜色

时间:2011-12-19 10:35:11

标签: objective-c uitableview

我有一个tableView包含几个af答案,用户将选择一个答案,如果答案为真,所选单元格将以绿色着色,否则:错误答案,两个单元格将是有色:红色选择,绿色选择。

我的问题是我无法通过indexPath的索引更改val1的值来找到正确的单元格。

这是我的tableView tableView:didSelectRowAtIndexPath方法:

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    NSNumber *value = [truerep objectAtIndex:0];
    NSUInteger val1 = [value integerValue];
    NSUInteger val2 = [indexPath row];

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    if (val1==val2) {//right answer so the color of the selected cell will be green
        cell.contentView.backgroundColor = [UIColor greenColor]; 
    }else {//wrong answer so 2 cells will be colored
        //the color of the selected cell will be red and the right cell will be green
        cell.contentView.backgroundColor = [UIColor redColor];

        // idk What to do here to change the value of indexpath by val1
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];  
}

1 个答案:

答案 0 :(得分:2)

为什么要这样做(更改indexPath值)?
只要用户在表视图中选择一行,就会调用此方法方法,[indexPath row]将为您提供该行索引。

问题可能来自于您在truerep数组中存储真实答案的索引的方式,无法将直接行索引与val1进行比较。

我不知道truerep[truerep objectAtIndex:0]要包含哪些内容,但在您的示例中,val1看起来像正确答案的行索引,并且它没有& #39; t对应真正的正确答案行索引。

此外,如果您希望两个单元格着色,则必须更改代码 在这里,使用if/else,当用户选择一行时,您只会获得一个彩色。

根据您的评论

编辑

您可能想要遍历所有行并确定要以红色和绿色着色的行。这是一个例子:

-(void)tableView:(UITableView *)tableView
 didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSUInteger rowIndex = [indexPath row];
    NSNumber *value = [truerep objectAtIndex:0];
    NSUInteger val1 = [value integerValue]; // index of the correct answer row
    UITableViewCell *cell;

    if(rowIndex = val1) { // only color the right cell in green
        cell = [tableView cellForRowAtIndexPath:ip];
        cell.contentView.backgroundColor = [UIColor greenColor];
    }
    else {
        for(rowIndex = 0; rowIndex < totalRowsCount; rowIndew += 1) {
            NSIndexPath *ip = [NSIndexPath indexPathWithIndex:rowIndex];
            cell = [tableView cellForRowAtIndexPath:ip];
            if(val1 == rowIndex) {
                cell.contentView.backgroundColor = [UIColor greenColor];
            }
            else {
                cell.contentView.backgroundColor = [UIColor redColor]; 
            }
        }
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];  
}

您肯定知道totalRowsCount ..

的价值