xcode 如何在 UITableView 中选择多行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5375122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 20:35:39  来源:igfitidea点击:

How to select Multiple rows in UITableView?

iphonexcodeuitableview

提问by Anand

I want multiple selection in UITableView and also its data into one array or in one dictionary...

我想在 UITableView 中进行多项选择,并将其数据放入一个数组或一个字典中...

回答by Syed Absar

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

    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];

    if ([selectedCell accessoryType] == UITableViewCellAccessoryNone) {
        [selectedCell setAccessoryType:UITableViewCellAccessoryCheckmark];
        [selectedIndexes addObject:[NSNumber numberWithInt:indexPath.row]];
    } else {
        [selectedCell setAccessoryType:UITableViewCellAccessoryNone];
        [selectedIndexes removeObject:[NSNumber numberWithInt:indexPath.row]];
    }

    [tableView deselectRowAtIndexPath:indexPath animated:NO];

}

selectedIndexeshas to be an array where you manage the selected cells indexes and utilize later accordingly.

selectedIndexes必须是一个数组,您可以在其中管理选定的单元格索引并稍后相应地使用。

回答by Mooner

Trying to do the same thing, but I'm seeing the "selected" checkmark accessory on other lines that were never selected when you scroll down the list. Also, deselecting one of the "phantom" items down the list causes the accessory to go away in the upper part of the list -- but the array is unaffected.

试图做同样的事情,但我在其他行上看到“已选择”复选标记附件,当您向下滚动列表时,这些行从未被选中。此外,取消选择列表下方的“幻影”项目之一会导致附件在列表的上部消失——但阵列不受影响。

Here's how I have it implemented:

这是我如何实施它:

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
if ([selectedCell accessoryType] == UITableViewCellAccessoryNone) {
    [selectedCell setAccessoryType:UITableViewCellAccessoryCheckmark];
    [selectedIndexes addObject:[NSNumber numberWithInt:indexPath.row]];
    NSLog(@"IVC selectedIndexes AddObject @ %d:", indexPath.row);
    NSLog(@"IVC selectedIndexes: %@", selectedIndexes);
    } else {
    [selectedCell setAccessoryType:UITableViewCellAccessoryNone];
    [selectedIndexes removeObject:[NSNumber numberWithInt:indexPath.row]];
    NSLog(@"IVC selectedIndexes RemoveObject @ %d:", indexPath.row);
    }
[tableView deselectRowAtIndexPath:indexPath animated:NO];
}

EDIT: Added solution: You need to put this in your "cellForRowAtIndexPath" code:

编辑:添加解决方案:您需要将其放入“cellForRowAtIndexPath”代码中:

    if ([selectedIndexes containsObject:[NSNumber numberWithInt:indexPath.row]]) [cell setAccessoryType:UITableViewCellAccessoryCheckmark];