ios - 添加和检索单元格到字典丢失单元格信息 swift3

标签 ios swift uitableview dictionary

我正在使用字典存储来自 cellForRowAt: TableView 的单元格,然后当单元格中的 textField 完成编辑时,我正在更新字典的内容以反射(reflect)新的细胞。这样一来,当单元格滚出屏幕,然后返回时,输入的值仍会显示。

当再次调用 cellForRowAt: 时,我从字典中检索单元格并将其返回,但是返回的单元格的 textField 不包含任何信息。

我已经通过使用与放在那里时相同的方法从字典中检索单元格来对此进行了测试,并且 textField 文本仍然存在。

这是在 textField 更改后替换单元格的代码:

func textFieldDidEndEditing(_ textField: UITextField) {
    if textField.tag == 0 {
        print("Replacing value in tableCells")
        let tempCell = tableCells["\(textField.tag)"] as! profileNameCell
        tempCell.profileName.text = textField.text
        tableCells["\(textField.tag)"] = tempCell
    } else {
        let tempCell = tableCells["\(textField.tag)"] as! profileInfoCell
        tempCell.infoField.text = textField.text
        tableCells["\(textField.tag)"] = tempCell
    }
}

这是 cellForRowAt: 中的代码:

let indexString = "\(indexPath.row)"

if tableCells[indexString] as! UITableViewCell == cellFiller {
    print("Replacing tableCells[\(indexString)] with cell")
    tableCells[indexString] = cell
    return cell
} else {
    print("Returning contents of tableCells[\(indexString)]")
    let replacementCell = tableCells[indexString] as! profileNameCell
    print("tableCells[\(indexString)] name info = \(replacementCell.profileName.text ?? "")")
    return replacementCell
}

最佳答案

不要自己管理单元格,这就是 UITableViewController 的用途。单元格被重复使用,因此您可能最终将相同的单元格添加到字典中的不同标签键。

相反,管理一个模型,并让 cellForRow 使用该模型来配置您的单元格。

我并不总是建议使用标记来跟踪您的文本字段,但为了简洁起见,这样做就可以了。只是想把它编出来,如果您有任何问题,请告诉我。

//definition
var strings = ["One", "Two", "Three"]

//number of sections
return 1

//number of rows
return strings.count

//cell for row - make a custom table cell with a textfield
cell.textField.text = self.strings[indexPath.row]
cell.textField.tag = indexPath.row

//textfield did end editing
strings[textField.tag] = textField.text
tableView.reloadData()

你也可以用字典代替。

关于ios - 添加和检索单元格到字典丢失单元格信息 swift3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45178539/

相关文章:

ios - 如何确保在访问核心数据模型之前已进行所有网络调用?

ios - 使用导航 Controller 处理数据持久性/流的正确方法?

ios - NSInternalInconsistencyException 原因 : 'Invalid update: invalid number of rows in section 0'

iOS; NSAutoreleasePool 过时了吗?

ios - 将调用切换到扬声器 - iOS 私有(private) api

swift - 不能使用函数内部定义的结构的重载运算符

ios - 自定义表格 View 单元格中 UITextField 的值在向上滚动和向下滚动时发生变化

ios - UITableView - IndexPath 始终首先返回 0 并点击 2 次以将正确的数据传递给 View Controller

ios - Xcode 8 和 Swift 3 中 Unresolved 标识符错误

ios - Swift:尝试使用 Facebook Open Graph 故事