gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:26:11 24 4
gpt4 key购买 nike

我正在使用字典存储来自 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com