文本字段中的swift 3 tableView复制自身

Posted

技术标签:

【中文标题】文本字段中的swift 3 tableView复制自身【英文标题】:swift 3 tableView in textfield copies itself 【发布时间】:2017-05-02 08:53:54 【问题描述】:

我的第一行文字 将自身复制到底线

当我滚动时, 数据的位置正在改变

【问题讨论】:

这是因为您的单元格正在被重复使用。具有值1, 2, 3 的单元格现在正在被重用,并且它们仍然具有第一次保存在其中的值。如果您保留以前条目中的值,请将它们单独保存,并在返回cellForRowAtIndexPath 中的单元格时,检查您是否已经在那里保存了值。 添加你的 cellForRowAtIndexPath 方法的代码 我这里的回答有详细解释:***.com/a/43164656/2179970 锡安佩雷斯我做过 不再复制但数据丢失 【参考方案1】:

UITableView Cell 中的数据是重复的,因为 Cell 被重复使用,因此您需要跟踪单元格的数据,可能您可以在按索引排列的数组中添加数据。

【讨论】:

【参考方案2】:

是的,这就是 UITableview dequeCells 的概念:因为它重用了单元格,所以如果有 100 个条目,一次只会创建有限数量的单元格以节省内存。 现在为了避免它,用具有所有值的数据源填充您的单元格视图。 如果您发现数据源中缺少某些值,请使用,例如:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! Tek101TableViewCell
    cell.selectionStyle = .none
    cell.siraLabel.text = ""
    cell.siraLabel.text = String(indexPath.row + 1) + ")"
    return cell

【讨论】:

【参考方案3】:
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! Tek101TableViewCell

    cell.selectionStyle = .none

    cell.siraLabel.text = String(indexPath.row + 1) + ")"



    return cell

【讨论】:

【参考方案4】:

您需要在文本字段委托方法中设置值,如下所示:(根据您的需要)

如果您在键盘上使用返回按钮

       func textFieldShouldReturn(_ textField: UITextField) -> Bool 
            let cell = textField.superview?.superview as! Tek101TableViewCell // track you view hierarchy
            cell. siraLabel?.text = textField.text
            textField.resignFirstResponder()
            return true
        

如果要跟踪值结束编辑方法

func textFieldDidEndEditing(_ textField: UITextField)
    let cell = textField.superview?.superview as! Tek101TableViewCell // track you view hierarchy
    cell. siraLabel?.text = textField.text

【讨论】:

【参考方案5】:

UITablview 单元格被重用,所以这件事会发生。要解决此问题,您必须将所有记录保存在一个全局数组变量中。

您可以在用户插入时将所有输入存储在数组或字典中。然后你必须为CellForRow中的每个单元格赋予这个数组值。

总之你只需要处理数组。

希望这会对你有所帮助。

【讨论】:

不...不要直接这样写。但是写成,cell.Textfield.text = sell.myArray[0] as! String这是例如 在此之前,您必须创建具有实际值的数组。如果没有值,则在该数组中添加默认值。然后在 cellforrow 中分配这个数组。 var myTexts: [字符串?]! func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell print("CellForRowAt: " + indexPath.row.description) let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! Tek101TableViewCell cell.oyuncu1TextField.text = myTexts[indexPath.row] 返回单元格

以上是关于文本字段中的swift 3 tableView复制自身的主要内容,如果未能解决你的问题,请参考以下文章

Swift:从 TableView 文本字段中检索值

如何在 swift 中使用文本字段文本“金额”向 tableview 添加额外的行

在 swift 中使用 tableview 和数组过滤器自动完成文本字段

选择器值到 tableView swift

如何在 swift 中使文本字段功能在 tableview 中

从 Swift (3.1) 表格视图中动态创建的单元格获取有序的文本字段数据