ios - 在 UItableView 中处理多个选定的行

标签 ios swift uitableview

我正在尝试获取所有选定行的文本标签,但我不知道如何搜索它,但没有从中得到任何帮助,所以我自己尝试了一些方法,但它不起作用我希望它是这样,我认为创建一个数组并对选定单元格的文本标签进行排序会起作用(是的,它工作正常),但是当取消选择一个单元格时,我想从我的数组中删除该特定单元格的文本标签,如果有人知道如何那么请告诉我

这是我的代码 -

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

    let cell = tableView.cellForRowAtIndexPath(indexPath)

    if (cell?.accessoryType == UITableViewCellAccessoryType.Checkmark){

        cell!.accessoryType = UITableViewCellAccessoryType.None;
        getTheChannelNames.removeAtIndex(getTheChannelNames.count - 1)



        print(getTheChannelNames.count)
           print(getTheChannelNames)



    }else{
        cell!.accessoryType = UITableViewCellAccessoryType.Checkmark;
        _ = self.ChannelList[indexPath.row]

        if (cell?.accessoryType == UITableViewCellAccessoryType.Checkmark){


                getTheChannelNames.append((cell?.textLabel?.text)!)
            print(getTheChannelNames.count)
               print(getTheChannelNames)
        }


    }
}

最佳答案

有几种方法可以处理这个问题。首先,跟踪所选文本标签的索引路径对于您来说极其重要。通过这样做,您可以避免排序。字典更适合这项任务。

var selectedTextLabels = [NSIndexPath: String]()

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = tableView.cellForRowAtIndexPath(indexPath)!
    cell.accessoryType = .Checkmark
    if let text = cell.textLabel?.text {
        selectedTextLabels[indexPath] = text
    }
}

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = tableView.cellForRowAtIndexPath(indexPath)!
    cell.accessoryType = .None
    selectedTextLabels[indexPath] = nil
}

如果选择了单元格,则文本标签将添加到词典中。相反,当它被取消选择时,它就会从字典中删除。

第二个解决方案是返回所有选定文本标签的方法:

func selectedTextLabels() -> [String]? {
    return self.tableView.indexPathsForSelectedRows?.flatMap {
        let cell = tableView.cellForRowAtIndexPath($0)!
        return cell.textLabel?.text
    }
}

它获取所有选定的索引路径并获取每个索引路径的文本标签。

关于ios - 在 UItableView 中处理多个选定的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34478968/

相关文章:

ios - 如何从另一个类中快速更新 label.text 的值

ios - 保持 TableView 之间的数组顺序?

iphone - 如何避免在 UITableViewCell 上滑动删除调用 setEditing

ios - UIImage 本身带有圆角

iphone - UILabels 与 UIWebView 一起滚动

swift - 如何使用一个变量/属性而不是将同一属性赋值三次?

swift - 我将如何限制 tableview 中的项目数量并自动加载更多?

ios - UITableViewCells 显示在其他类型的单元格上

ios - Swift 中的 Firebase。无法将类型 'NSNull' 的值转换为 'NSDictionary'

ios - 异步下载图像到 NSData 和缓存