iOS学习笔记--tableView多选实现

本文介绍如何使用iOS中TableView的内置方法实现多选功能。通过设置编辑模式并允许多选,可以轻松地让用户选择多个选项,并通过代理方法记录用户的操作。

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

本文介绍使用tableView自带的方法来实现多选功能。
@property(nonatomic,strong)UITableView *  tmptabelView;
@property(nonatomic,strong)NSMutableArray * saveArray;
@property(nonatomic,strong)NSMutableArray * array;
self.array = [NSMutableArray arrayWithObjects:@"普通话",@"英语",@"法语",@"俄语",@"日语",@"韩语",@"德语",@"西班牙语",@"泰语",@"小语种",nil];

self.saveArray = [NSMutableArray array];

self.tmptabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 300, 400)];

    [self.tmptabelView setBackgroundColor:[UIColor whiteColor]];


    [self.tmptabelView setDelegate:self];

    [self.tmptabelView setDataSource:self];

    self.tmptabelView.editing = YES;

    self.tmptabelView.allowsMultipleSelectionDuringEditing = YES;

    [self.view addSubview:self.tmptabelView];
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;

}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * ID = @"ID";

    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];

    if (!cell)
    {
        cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:ID];
    }

    [cell.textLabel setText:[NSString stringWithFormat:@"%@",self.array[indexPath.row]]];

    cell.selectedBackgroundView = [[UIView alloc] init];

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{   
  //将选中的元素保存 
  [self.saveArray addObject:self.array[indexPath.row]];

}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{


    if (self.array.count > indexPath.row)
    {

        //将选中的元素移除
        if (self.saveArray.count > 0)
        {

            [self.saveArray removeObject:self.array[indexPath.row]];

        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值