【问题标题】:Adding and retrieving cells to dictionary losing cell info swift3在字典中添加和检索单元格丢失单元格信息 swift3
【发布时间】:2017-12-24 00:22:37
【问题描述】:

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

【问题讨论】:

    标签: ios swift uitableview dictionary


    【解决方案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()
    

    你也可以用字典来代替。

    【讨论】:

    • 完美 - 工作愉快,我使用字典而不是数组,因为表中的每个单元格都是配置文件创建字段的一部分,我不希望它们出现故障。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多