##TableView实现多选,并限制选择个数

本文记录了如何在TableView中实现多选功能并限制选择的个数。通过设置tableView.allowsMultipleSelection为YES,结合didSelectRowAtIndexPath和didDeselectRowAtIndexPath方法来控制cell的背景颜色以指示选中状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

TableView实现多选,并限制选择个数

今天帮同学倒腾了了这个需求,由于手生,弄了快一个小时才完全弄好。因此记录下来,涨涨经验。

如题:要实现tableView的多选,并要限制个数N。

  • 思路:

    1. 先设置允许多选:tableView.allowsMultipleSelection = YES;
    2. 设置cell默认背景颜色ColorB
    3. 在didSelectRowAtIndexPath方法中判断当前选中了多少个,如果少于或等于N个,则把当前选中的cell的backgroundColor或者cell.contentView 的backgroundColor设置为指定的颜色ColorA
    4. 在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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值