UITableView多选

时间:2012-07-30 15:33:09

标签: objective-c xcode uitableview

我有一个uitableview,其中有50行来自预定义的nsarray。

如何选择多个行,一次最多允许3行,并在选中时显示检查,取消选中后删除检查/

我是xcode的新手,非常感谢任何帮助。谢谢。

2 个答案:

答案 0 :(得分:3)

您的数据需要跟踪它是否被选中。

两种常见方法是:预定义数组中的每个对象都有一个BOOL,用于指示是否选中它,或者保留第二个仅包含对所选对象的引用的数组。由于您被限制为三个选择,第二个选项可能会更好。

当有人选择表格中的单元格时,您可以更改相关对象的选择状态,切换其BOOL或在额外数组中添加/删除它。这也是检查您是否已经拥有尽可能多的选择的地方。如果选择已更改,则告诉您的表重新加载数据。

cellForRowAtIndexPath:中,检查对象是否被选中并相应地标记。

答案 1 :(得分:3)

int counter = 0; //keep track of how many rows are selected
int maxNum = 3; //Most cells allowed to be selected

//Called when the user selects a row
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    //If the cell isn't checked and there aren't the maximum allowed selected yet
    if (cell.accessoryType != UITableViewCellAccessoryCheckmark && counter < maxNum)
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        counter++;
    }
    else if (counter >= maxNum) return; //Don't do anything if the cell isn't checked and the maximum has been reached
    else //If cell is checked and gets selected again, deselect it
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
        counter--;
    }
}

您可能还希望保留所选单元格的索引数组,以防您想对其中的数据执行某些操作。如果您不知道如何操作,请告诉我,我将添加代码。

注意:

  • 您需要实现表视图委托协议才能正确调用此方法。
  • 这不是“最好”的方法(使用单元格内容来跟踪选择通常不受欢迎)但这很容易。
  • 您可能会遇到细胞重用问题。如果要解决此问题,请存储单元格的索引并在cellForRowAtIndexPath
  • 中设置附件类型