UITableViewCell 添加 checkbox 多选 (二)

来源:互联网 发布:百度人工智能识别卡 编辑:程序博客网 时间:2024/05/03 16:23

其实苹果原生就有cell的多选,不过做出来的效果是这样的


我的大概逻辑是这样考虑的  

(一)先考虑右上角button的事情,平时是delete,当cell时编辑状态就换成done

(二)考虑cell的编辑状态

其实cell有一个函数可以直接对cell进行编辑

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
    
}
下面这两个是执行cell选中和非选中时的转态
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
 
}
接下来很明显就是对数组进行操作了,定义两个可变数组
@property(nonatomic,strong)NSMutableArray * list;
@property(nonatomic,strong)NSMutableArray * removeList;

在viewDidLoad里面操作右导航,并且把两个数组初始化

- (void)viewDidLoad {

    [super viewDidLoad];
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithTitle:@"Delecte" style:UIBarButtonItemStyleBordered target:self action:@selector(editCell:)];
    self.navigationItem.rightBarButtonItem = item;
    
    if (self.list == nil) {
        self.list = [[NSMutableArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5", nil];
    }
    self.removeList = [[NSMutableArray alloc] init];
   
    
}

- (void)editCell:(id)sender{
    [self.tableView setEditing:!self.tableView.editing animated:YES];
    if (self.tableView.editing) {
        [self.navigationItem.rightBarButtonItem setTitle:@"Done"];//cell可编辑状态右导航切换主题
    }else{//进入不可编辑转态,就是还原了
        [self.navigationItem.rightBarButtonItem setTitle:@"Delete"];
        if (self.removeList.count>0) {//大于零就进行移除操作

//逻辑:1,移除数组大于零,list执行移除remove里面的数组

              2.cell刷新数据

              3,remove清零

            [self.list removeObjectsInArray:self.removeList];
            [self.tableView reloadData];
            [self.removeList removeAllObjects];
        }
        
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.list.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ID"];
    }
    cell.textLabel.text = self.list[indexPath.row];
    return cell;

}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.removeList addObject:self.list[indexPath.row]];//当选中时操作移除的数组增加选中转态数组里面的元素
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.removeList removeObject:self.list[indexPath.row]];//非选中就移除
}


1 0
原创粉丝点击