##TableView实现多选,并限制选择个数
2016-03-30 10:30
435 查看
TableView实现多选,并限制选择个数
今天帮同学倒腾了了这个需求,由于手生,弄了快一个小时才完全弄好。因此记录下来,涨涨经验。如题:要实现tableView的多选,并要限制个数N。
思路:
先设置允许多选:tableView.allowsMultipleSelection = YES;
设置cell默认背景颜色ColorB
在didSelectRowAtIndexPath方法中判断当前选中了多少个,如果少于或等于N个,则把当前选中的cell的backgroundColor或者cell.contentView 的backgroundColor设置为指定的颜色ColorA
在didDeselectRowAtIndexPath方法中把取消选中的cell的backgroundColor或者cell.contentView 的backgroundColor设置为指定的颜色ColorB
注意
一定要在didDeselectRowAtIndexPath中设置取消后cell的背景颜色
代码如下:
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //允许多选 self.tableView.allowsMultipleSelection = YES; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return 10; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPathP{ UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; } cell.textLabel.text = [NSString stringWithFormat:@"第%ld行", indexPathP.row]; cell.selectionStyle = UITableViewCellSelectionStyleNone; return cell; } //取消选择cell -(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; cell.backgroundColor = [UIColor whiteColor]; NSLog(@"%@",indexPath); } //选择cell -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; if(tableView.indexPathsForSelectedRows.count <= 7) { cell.backgroundColor = [UIColor grayColor]; } } @end
相关文章推荐
- 三大WEB服务器(Apache、Nginx、Lighttpd)对比
- 算法训练 删除数组零元素
- Http协议总结
- Java基础知识强化之IO流笔记83:NIO与IO
- 乙女心,养的第一株多肉小植物
- 求数组中未出现的最小正整数
- Linux时间子系统之(五):POSIX Clock
- 题目记录
- cygwin1.dll is missing from your computer
- file_operations -- file -- inode
- Linux 系统调用
- Linux 的虚拟文件系统--各结构之间的联系
- I-O 端口和 I-O 内存
- 9.4. 使用 I/O 内存
- Linux 2.6内核的编译步骤及模块动态加载
- experiment目录递归,indent C standard style
- 递归法遍历目录查找文件
- 递归遍历目录的shell脚本
- 在sed中怎么样产生控制字符^M
- ubuntu中fatal error: mysql.h: No such file or directory