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