1、问题
奇怪的BUG:
用的是UITableView 每个cell 里面加了一个 checkbox框 , 通过两个图片来切换 选中、未选中
点击事件如下,但是发现:如果选中第1个cell, 那么第8个 第16个。。。。(通过滚动。。出来的cell)都被选中了, 这个Bug原来是缓存造成的。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPathanimated:YES];
UITableViewCell *cell = (UITableViewCell*)[tableViewcellForRowAtIndexPath:indexPath];
UIImageView *checkedImage = (UIImageView *)[cell.contentViewviewWithTag:checkedTag];
NSUInteger row = [indexPathrow];
//Airconditioner ac 是UI的业务数据model,也就是当ac 的checked 是YES的时候,UI为选中图片,反之。。。
Airconditioner *ac = [acArrayobjectAtIndex:row];
if (ac.checked ==nil) {
ac.checked=@"NO";
}
if ([ac.checkedisEqualToString:@"NO"]) {
ac.checked =@"YES";
checkedImage.image = [UIImageimageNamed:@"checked.png"];
cell.backgroundColor = [UIColorcolorWithRed:223.0/255.0green:230.0/255.0blue:250.0/255.0alpha:1.0];
}else {
ac.checked =@"NO";
checkedImage.image = [UIImageimageNamed:@"unchecked.png"];
cell.backgroundColor = [UIColorwhiteColor];
}
}
2、解决办法
-(UITableViewCell *)customCellWithOutXib:(UITableView *)tableView withIndexPath:(NSIndexPath *)indexPath{
//定义标识符
staticNSString *customCellIndentifier =@"CustomCellIndentifier";
UITableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:customCellIndentifier];
//定义新的cell
if(cell ==nil){
//使用默认的UITableViewCell,但是不使用默认的image与text,改为添加自定义的控件
cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:customCellIndentifier];
。。。。。。。。。。。其它UI 元素。。。。。。。。。。。。
//checked图片
CGRect checkedRect =CGRectMake(320,15, 30,30);
UIImageView *checkedImageView = [[UIImageViewalloc]initWithFrame:checkedRect];
checkedImageView.tag =checkedTag;
checkedImageView.image = [UIImageimageNamed:@"unchecked.png"];
//为图片添加边框
CALayer *checkedLayer = [checkedImageViewlayer];
checkedLayer.cornerRadius =7;
checkedLayer.borderColor = [[UIColorwhiteColor]CGColor];
checkedLayer.borderWidth =1;
checkedLayer.masksToBounds =YES;
[cell.contentViewaddSubview:checkedImageView];
}
//获得行数
NSUInteger row = [indexPathrow];
UIImageView *checkedImage = (UIImageView *)[cell.contentViewviewWithTag:checkedTag];
// ac 是UI的数据model,也就是当ac 的checked 是YES的时候,UI为选中图片,反之。。。
if (ac.checked ==nil) {
ac.checked=@"NO";
}
if ([ac.checkedisEqualToString:@"NO"]) {
checkedImage.image = [UIImageimageNamed:@"unchecked.png"];
cell.backgroundColor = [UIColorwhiteColor];
}else {
checkedImage.image = [UIImageimageNamed:@"checked.png"];
cell.backgroundColor = [UIColorcolorWithRed:223.0/255.0green:230.0/255.0blue:250.0/255.0alpha:1.0];
}
return cell;
}