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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值