在iOS中选择多个表视图单元格的本机方式

时间:2013-12-20 03:37:41

标签: ios iphone uitableview ios7

我有一个用例,我需要在uitableview中选择多个tableviewcells。选择单元格后,我将使用选择的结果进行处理。

如何以标准iOS/UIKit方式完成此操作?我会使用什么控件?

1 个答案:

答案 0 :(得分:1)

要处理此类情况,您需要一个额外的数组来保留所选项目。

在您的didSelectRowAtIndexPath中,您需要根据当前状态(已选择/取消选择)推送/弹出所选项目

实现如下:

    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
   {
       UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
       if(cell.accessoryType == UITableViewCellAccessoryNone)
       {
           cell.accessoryType = UITableViewCellAccessoryCheckmark;
           [selectedItemsArray addObject:[yourDataSourceArray objectAtIndex:indexPath.row]];
       }
       else
       {
           cell.accessoryType = UITableViewCellAccessoryNone;
           [selectedItemsArray removeObject:[yourDataSourceArray objectAtIndex:indexPath.row]];
       }
       [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }

您还需要修改cellForRowAtIndexPath之类的内容:

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
   {
       NSString *cellIdent = @"cell";
       UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdent];
       if(cell == nil)
       cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdent];
       //Adding items to cell
       if([selectedItemsArray containsObject:[yourDataSourceArray objectAtIndex:indexPath.row]])
       {
           cell.accessoryType = UITableViewCellAccessoryCheckmark;
       }
       else
       {
           cell.accessoryType = UITableViewCellAccessoryNone;
       }
       return cell;
    }

您可以将自定义图像用于所选状态,而不是显示原生UITableViewCellAccessoryCheckmark。您可以参考本教程了解custom accessory-view