【问题标题】:Textfield values deleted when scrolling tableview?滚动表格视图时删除的文本字段值?
【发布时间】:2020-05-25 11:08:31
【问题描述】:

我有一个带有文本字段的 tableview 单元格,但是当我添加新行并向上或向下滚动 tableview 时,删除的文本字段值消失了。我在 2015 年对之前的问题进行了大量研究,但没有正确回答。我该如何解决这个问题?如果它适用于此,我该如何使用文本字段委托方法?这是我的代码:

var i = 0

while i <= taskArrForRead.count {
  let indexPath = IndexPath(row: i, section: 0)
  let cell = self.tableView.cellForRow(at: indexPath) as? taslakDuzenlemeCell

  if let item = cell?.taslakTextField.text! {
    arrayOfNames.append(item)
  }
  i = i + 1
}

在此代码中,我从 tableview 获取所有文本字段值,但如果 tableview 滚动消失,值将使用默认值。我该如何解决?谢谢。

这是我的表格视图代码:

extension taslakOlusturmaController: UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return taskArrForRead.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "taslakCell", for: indexPath) as! taslakDuzenlemeCell

        cell.taslakTextField.text = taskArrForRead[indexPath.item]
        cell.taslakTextField.delegate = self
        return cell
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        print(textField.text!)
        self.arrayOfNames.append(textField.text!)
    }

    func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "taslakCell", for: indexPath) as! taslakDuzenlemeCell
        cell.taslakTextField.text = taskArrForRead[indexPath.item]
        print(arrayOfNames[indexPath.item])
    }
}

使用textfield delegate 方法,我可以获得已删除的文本字段值,但无法将其再次带到文本字段。用户再次滚动后看不到值,我也可以使用didEndDisplaying cell 方法获取已删除的值。

【问题讨论】:

  • 因为单元格是重复使用的,你需要将文本字段的值保存在viewcontroller里面的一个变量中
  • 显示你的tableView代码
  • @NayanDave 我在这里添加了。

标签: swift uitableview uitextfield


【解决方案1】:

您可以使用PrepareForReuse 方法在重新创建单元格时重新设置文本。

【讨论】:

  • 感谢您的回复。我该如何准确地使用它?我需要在这个方法中调用 textfield 吗?抱歉,我是 swift 的新手。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多