如何存储选定行的数组?

时间:2015-08-25 19:10:10

标签: ios arrays swift uitableview

在我的代码中,我有一个表视图,用于加载使用我的应用程序的用户名。当用户选择一行时,它将显示一个复选标记。我想要做的是保存一个包含所有选定行的数组(该数组将包含名称)。我找到了一些信息,但我还在学习iOS编程,我不知道Obj-c。

这是我到目前为止所做的:

var selectedMembers = [String]?
 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.names?.count ?? 0
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("UserCell") as! UITableViewCell

        cell.textLabel!.text = names![indexPath.row]

        return cell
    }


func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
    selectedMembers = Array()
    if let cell = tableView.cellForRowAtIndexPath(indexPath) {

        if cell.accessoryType == .Checkmark
        {
            cell.accessoryType = .None

            self.selectedMembers?.remove(indexPath)

        }
        else
    {
        cell.accessoryType = .Checkmark
        self.selectedMembers?.append(indexPath)
        }
    }
}

2 个答案:

答案 0 :(得分:2)

要获取名称,您需要使用所选行,并使用名称将该行的条目输入到数组中。

要获取indexpath的行,您可以使用

indexPath.row

要获取您的会员姓名,请使用

names![indexPath.row-1]

当然,您可以使用

将其保存到您的数组中
self.selectedMembers?.append(names![indexPath.row-1])

删除您需要添加额外步骤的项目

self.selectedMembers?.removeAtIndex(selectedMembers.indexOf(names![indexPath.row-1]))

答案 1 :(得分:0)

您可以使用didSelectRowAtIndexPath和didDeselectRowAtIndexPath委托方法来跟踪表中的索引路径。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    selectedIndexPaths.append(indexPath)

}

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {

    if let index = find(selectedIndexPaths, indexPath) {
        selectedIndexPaths.removeAtIndex(index)
    }

}

然后,您可以使用索引路径回溯并获取所选对象。

相关问题