2011-12-19 150 views
0

我有一個tableView包含幾個af答案,用戶將選擇一個答案,如果答案爲true,則選中的單元格將被綠色着色,否則:錯誤答案,兩個單元格將被着色:紅色選擇,右側綠色。當單元格選中時更改單元格的顏色

我的問題是,我不能通過val1索引更改indexPath的值以找到正確的單元格。

,這裏是我的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]; 
} 

回答

2

爲什麼要那麼做(改變indexPath值)?
只要用戶在表格視圖中選擇一行,就調用此方法方法,[indexPath row]將爲您提供該行索引。

該問題可能來自您存儲truerep數組中真實答案索引的方式,無法將直接行索引與val1進行比較。

我不知道是什麼truerep[truerep objectAtIndex:0]是想控制,但在你的榜樣,val1看起來像正確答案的行索引,並且它不符合真正的正確答案,行索引。另外,如果你想要兩個單元格被着色,你將不得不改變你的代碼。
在這裏,使用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值..

+0

是VAL1是整數值,它包含了正確的答案 – 2011-12-19 10:51:33

+0

所以有什麼問題的指標?它不符合行索引? – 2011-12-19 10:52:23

+0

truerep是所有正確答案的索引數組 – 2011-12-19 10:52:37

相關問題