tableviewcell的单选和多选

来源:互联网 发布:2016网络最热门的游戏 编辑:程序博客网 时间:2024/05/17 05:55

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

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

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

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

-(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;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

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

    //当上下拉动的时候,因为cell的复用性,我们需要重新判断一下哪一行是打勾的    if (_selIndex == indexPath) {        cell.accessoryType = UITableViewCellAccessoryCheckmark;    }else {        cell.accessoryType = UITableViewCellAccessoryNone;    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

这样就实现的单选的功能了 
这里写图片描述

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

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

初始化一下

_selectIndexs = [NSMutableArray new];
  • 1
  • 1

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

-(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]; //添加索引数据到数组    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

当然也需要在下面的方法做处理 
这里写图片描述

//设置勾    cell.accessoryType = UITableViewCellAccessoryNone;    for (NSIndexPath *index in _selectIndexs) {        if (index == indexPath) { //改行在选择的数组里面有记录            cell.accessoryType = UITableViewCellAccessoryCheckmark; //打勾            break;        }    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

复选: 
这里写图片描述

demo下载地址:https://github.com/yybchl/yoyo.git

0 0
原创粉丝点击