您的位置:首页 > 移动开发 > IOS开发

iOS使用NSMutableSet记录cell控件选中状态避免cell重用问题

2016-10-31 10:12 661 查看
我在tableView上面有个button,当我选中button的时候,上滑页面发现选中的状态没有了,但是数组里面添加的button tag值还在(类似于购物车那种方式)很是蛋疼,幸亏还有NSMutableSet来拯救我们啊 哈哈 废话不多说,直接看代码

1、首先我们定义一个NSMutableSet的属性

//用来记录选中的状态

@property (nonatomic, strong)NSMutableSet *selectdeSet;

2、初始化

self.selectdeSet = [NSMutableSet set];


3、在需要记录状态的地方记录选中状态,比如现在记录每行cell的tag值

-(UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *identifier = @"cell";
XiaLaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[XiaLaTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
XiaLaModel *model = self.arrModel[indexPath.row];
cell.xialaModel = model;
cell.thirdLabel.tag = 100 + indexPath.row;
[cell.thirdLabel addTarget:self action:@selector(chooseAction:) forControlEvents:(UIControlEventTouchUpInside)];
//这个是NSMutableSet 判断这个集合中是否存在传入的对象,返回Bool值,如果是则此cell为选中状态 否则为非选中状态
if ([self.selectdeSet containsObject:[NSString stringWithFormat:@"%ld", 100 + indexPath.row]]) {
cell.thirdLabel.selected = YES;
[cell.thirdLabel setTitleColor:[UIColor whiteColor] forState:(UIControlStateSelected)];
}
return cell;


}

-(void)chooseAction:(UIButton *)sender

{

if (sender.selected == NO) {
sender.selected = YES;
[sender setTitleColor:[UIColor whiteColor] forState:(UIControlStateSelected)];
//向数组中添加选中的对象
[self.dataArray addObject:[NSString stringWithFormat:@"%ld", sender.tag]];
//向NSMutableSet动态添加选中的对象
[self.selectdeSet addObject:[NSString stringWithFormat:@"%ld", sender.tag]];
} else {
sender.selected = NO;
for (int i = 0; i < self.dataArray.count; i++) {
if ([[self.dataArray objectAtIndex:i] isEqualToString:[NSString stringWithFormat:@"%ld",(long)sender.tag]]) {
// 删除数组中选中的对象
[self.dataArray removeObjectAtIndex:i];
//删除NSMutableSet中选择的对象
[self.selectdeSet removeObject:[NSString stringWithFormat:@"%ld", sender.tag]];
}
}
}


}

到此,使用NSMutableSet记录选中状态的方法结束,我们只需要注意的是,当你给数组添加对象的时候,记得给NSMutableSet添加对象,同样当你删除掉数组里面对象的时候记得删除点NSMutableSet中的对象
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios 控件 tag class