最新消息:iOS编程开发交流群(6906921) ,Mac.Cocoa开发交流群(7758675) 欢迎iOS/macOS开发编程爱好及学习者加入!

iOS开发之系统方式进行UITableView多选(不用数组维护选中状态)

iOS 天狐 11545浏览 0评论

e ..一般多选 大家会想到使用一个自定义数组与indexPath进行关联。进行多选。进行ui变化。

其实UITableView已经自带了多选功能,状态由UITableView本身维护。代码很简单。直接上代码了。

一.设置可以多选

//非编辑模式下进行多选
self.tableView.allowsMultipleSelection = YES;
//编辑模式下也有对应方法
//self.tableView.allowsMultipleSelectionDuringEditing = YES;

现在就可以进行多选啦。

二.设置选中后Cell的accessoryType或者自定义的图标。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"SelectCell";
    
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:CellIdentifier];
    UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    cell.tintColor = [UIColor grayColor];
//    cell.textLabel.textColor = self.titleColor?:[UIColor blackColor];
    cell.textLabel.text = [[_newsArray objectAtIndex:indexPath.row] objectForKey:@"value"];

    //防止重用后状态错乱.如果已经被选中,改变cell样式
    if ([[tableView indexPathsForSelectedRows] containsObject:indexPath]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //如果已经被选中,改变cell样式
    UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    //如果取消选中,改变cell样式
    UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryNone;
}

三.获取选中后的所有行或者数据

self.tableView.indexPathsForSelectedRows 就行当前选中的所有的行,重用也不会使他数据错误。相当于我们自己维护的状态数组啦。

NSMutableArray *selectItems =[NSMutableArray array];
for (NSIndexPath *indexPath in self.tableView.indexPathsForSelectedRows) {
   NSDictionary *item = [_newsArray objectAtIndex:indexPath.row];
   [selectItems addObject:item];
}

 

Done!

转载请注明:天狐博客 » iOS开发之系统方式进行UITableView多选(不用数组维护选中状态)

微信 OR 支付宝 扫描二维码
为天狐 打赏
非常感谢你的支持,哥会继续努力!
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址