我有一个用例,我需要在一个可选视图中选择多个tableviewcells。选择单元格后,我将使用选择的结果进行处理。在iOS中选择多个表格视图单元格的原生方式
我该如何做到这一点标准iOS/UIKit
的方式?我将使用哪些控件?
我有一个用例,我需要在一个可选视图中选择多个tableviewcells。选择单元格后,我将使用选择的结果进行处理。在iOS中选择多个表格视图单元格的原生方式
我该如何做到这一点标准iOS/UIKit
的方式?我将使用哪些控件?
为了处理这种情况,您需要一个额外的数组来保存选定的项目。
而在你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。
为什么要使用另一个数组?一旦用户选择了相应的行,只需在模型中添加一个标志即可。 – Till
@Till:是的,这也是一个很好的解决方案。我使用数组轻松管理选定的项目。如果用户需要对所有选定的对象进行操作。在阵列中很容易。如果更改在模型对象中。您需要首先找到所有选定的对象,然后对其进行修改。但我没有想到,这是一个很棒的主意。感谢分享 !!! –
你是什么意思“我将使用什么控件”? – Till
你看过UITableView的文档吗? – rmaddy
@Atma,看看这篇文章的答案,或者rmaddy说看看文档。这里是链接的人http://stackoverflow.com/questions/18176907/uitableviewcellaccessorycheckmark-multiple-selection-detect-which-cells-selected –