当单元格选中时更改单元格的颜色
问题描述:
我有一个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];
}
答
为什么要那么做(改变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
值..
是VAL1是整数值,它包含了正确的答案 – 2011-12-19 10:51:33
所以有什么问题的指标?它不符合行索引? – 2011-12-19 10:52:23
truerep是所有正确答案的索引数组 – 2011-12-19 10:52:37