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

时间:2017-07-18 23:11:56

标签: ios swift uitableview dictionary

我正在使用字典来存储cellForRowAt:上的表格视图中的单元格,然后当单元格中的textField完成编辑时,我正在更新字典的内容以反映新单元格。这样,当单元格滚出屏幕,然后返回输入的值仍然显示。

再次调用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
}

1 个答案:

答案 0 :(得分:1)

不要自己管理细胞,这就是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()

您也可以使用字典来完成。