您的位置:首页 > 其它

##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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: