美文网首页iOS DeveloperiOS 开发
40行代码实现UITableViewCell的多选操作

40行代码实现UITableViewCell的多选操作

作者: iOScoderZZJ | 来源:发表于2016-08-25 11:16 被阅读150次

前言

UITableViewCell的多选在很多应用中都是很常见的操作,一般的开发者认为这是一个很复杂的操作,包括我,知道我在网上看到了一个demo,发现原来实现UITableViewCell的多选真的只需要40行代码左右,有些写法让我耳目一新,原来真的只有这么简单

一言不合 上代码

- (void)viewDidLoad {
    [super viewDidLoad];
//tableView和dataArray 都定义了属性,没有贴出
    self.tableView = [[UITableView alloc] init];
    self.tableView.frame = self.view.bounds;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    self.dataArray = [NSArray arrayWithObjects:@"数据1",@"数据2",@"数据3",@"数据4",@"数据5",nil];
//开启tableView的编辑模式
    [self.tableView setEditing:YES animated:YES];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];;
    cell.textLabel.text = self.dataArray[indexPath.row];
    return cell;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
//必须返回这个,返回这个才是我们想要的效果(非选中cell左边有个圆圈,选中后有蓝色的对勾,下面有图)
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self updateDataWithTableview:tableView];
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self updateDataWithTableview:tableView];
}
- (void)updateDataWithTableview:(UITableView *)tableView{
    NSArray *indexpaths = [tableView indexPathsForSelectedRows];
    NSMutableArray * selectedItems = [NSMutableArray array];
    for (NSIndexPath *indexpath in indexpaths) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexpath];
        [selectedItems addObject:cell.textLabel.text];
    }
    NSLog(@"选中的cell上的标题数组: %@ \n 选中的行数组:  %@",[selectedItems componentsJoinedByString:@";"],indexpaths);
}

来我们看看效果图

WechatIMG6.jpeg

看看控制台的打印

WechatIMG4.jpeg

多选过cell之后,我们可以根据数组的信息拿到对应的模型或者相应的数据进行接下来的操作

进阶

以下全部是我找到的相关的资料<a href="http://blog.csdn.net/dick_china/article/details/7915858">创建操作/删除多行数据的UITableView的细节</a>(侵权删) <a href="http://blog.csdn.net/lin_hy/article/details/42496361">tableview 编辑状态下,UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert 多选的时候,替换圆圈图片</a>(侵权删) 实现更多的操作,无非是重写cell的一些方法,达到相应的效果,今天就分享到这里吧,干货不是很多,主要是借鉴了别人的一些资料

我是iOS开发的小菜鸡,希望成为一只雄鹰
旅途很长,还需修行

相关文章

网友评论

    本文标题:40行代码实现UITableViewCell的多选操作

    本文链接:https://www.haomeiwen.com/subject/zqzosttx.html