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的复用,需要在下面的方法再判断是谁打勾
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 {
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;
}
}
复选: