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

假如现在tableViewCell上有一个button,当我选中button的时候,上下滑动,发现button选中的状态消失了,但是数组里面添加的button.tag值还在……
如何避免这个问题呢,我们使用NSMutableSet来解决这个问题......
1、首先,我们定义一个NSMutableSet的属性

@property (nonatomic, strong)NSMutableSet *selectdeSet; //记录选中状态
@property (nonatomic, strong)NSMutableArray *dataArray;//数组中添加选中时候的tag值 

2、viewdidload里面初始化

self.selectdeSet = [NSMutableSet set];
self.dataArray = [NSMutableArray array];

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使用NSMutableSet记录cell控件选中状态避免cell重用问题)