tableView中cell的单选或者复选

iOS开发中,有时候需要实现tableView中cell的单选或者复选,这里举例说明了怎么简单的实现

首先自己创建一个列表,实现单选,先定义一个变量记录每次点击的cell的indexPath:

@property (assign, nonatomic) NSIndexPath *selIndex;//单选,当前选中的行

然后在下面的代理方法实现代码

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //之前选中的,取消选择
    UITableViewCell *celled = [tableView cellForRowAtIndexPath:_selIndex];
    celled.accessoryType = UITableViewCellAccessoryNone;
    //记录当前选中的位置索引
    _selIndex = indexPath;
    //当前选择的打勾
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
}

当然,上下滑动列表的时候,因为cell的复用,需要在下面的方法再判断是谁打勾


这里写图片描述
    //当上下拉动的时候,因为cell的复用性,我们需要重新判断一下哪一行是打勾的
    if (_selIndex == indexPath) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

这样就实现的单选的功能了


这里写图片描述

接下来说一下多选的实现,和单选不同,多选是一组位置坐标,所以我们需要用数组把这一组选中的坐标记录下来,定义一个数组

@property (strong, nonatomic) NSMutableArray *selectIndexs;//多选选中的行

初始化一下

_selectIndexs = [NSMutableArray new];

接下来还是在下面的代理方法实现代码

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //获取到点击的cell
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) { //如果为选中状态
        cell.accessoryType = UITableViewCellAccessoryNone; //切换为未选中
        [_selectIndexs removeObject:indexPath]; //数据移除
    }else { //未选中
        cell.accessoryType = UITableViewCellAccessoryCheckmark; //切换为选中
        [_selectIndexs addObject:indexPath]; //添加索引数据到数组
    }
}

当然也需要在下面的方法做处理


这里写图片描述
//设置勾
    cell.accessoryType = UITableViewCellAccessoryNone;
    for (NSIndexPath *index in _selectIndexs) {
        if (index == indexPath) { //改行在选择的数组里面有记录
            cell.accessoryType = UITableViewCellAccessoryCheckmark; //打勾
            break;
        }
    }

复选:


这里写图片描述
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容