我在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中的对象