在tableview中滚动后,UITextField和UITextView消失了吗?

时间:2017-09-25 10:56:29

标签: ios swift swift3

我正在使用 UItextfield UItextview ,当我在textview和textfield中输入内容并在tableview中滚动时。数据将消失,有时文本字段和textview中的数据得到了重复。

代码:

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 

  { 
     var cell = table_view_one.dequeueReusableCell(withIdentifier: "first_cell", for: indexPath) as! first_cell 
     if(indexPath.row>0)
     {
         cell.add_new_btn.setImage(UIImage(named:"close"), for: .normal)
     } 
     cell.delegate = self return cell 
  }

UITextField and UITextView disappears after scrolling in tableview

4 个答案:

答案 0 :(得分:0)

问题: 必须是您正在重复使用单元格并且不保存文本字段的值(您键入的值)。 解: 保存您正在键入的文本,然后在再次出列时将其传递回单元格。

答案 1 :(得分:0)

您可以创建一个包含textfield文本的数组。首先,启动具有单元数量容量的数组,并为每个索引添加空字符串。

然后,当你在textFieldDidEndEditing中的任何文本字段中写入时,通过从point(textfield)获取单元格索引将该文本保存到适当索引处的数组。

在cellForRow中,只需根据indexPath.row

分配数组的值

答案 2 :(得分:0)

在重复使用单元格的同时,它会在某些情况下再次创建新内存。因此,所有小部件和组件都属于单元格显然会重生。为了维护小部件的先前状态,需要通过持久保存旧状态数据来为新创建的小部件设置每次旧状态。

在您的情况下,它需要通过协议方法从单元格中保留在TextField或TextView中输入的文本。以下是实现相同目标的简要方法。

<强> Cell.swift

1.创建一个协议,将文本传递给ViewController,如:

 protocol CellDelegate {
    func textFieldText(cell: UITableViewCell, text: String)
 }

2.每次文本更新时触发委托方法。如果您在textFieldShouldEndEditing中调用该方法,则会错过一个案例,例如,如果您可以使用保存按钮,则在键盘中输入带有“退出”按钮的文本,如果您可以点击它,则不会发生该事件所以实际文本不会在持久模型中更新。因此,每次更改文本时最好调用委托,shouldChangeCharactersInRange方法在这种情况下是选择,实现将如下:

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let result = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) ?? string
        delegate.textFieldText(self, text: result)
    }

<强> ViewController.swift

1.在控制器中创建局部变量以保存每个TextField或TextView数据,如:

var textFieldText = ""

2.在cellForRowAt方法中为单元格分配委托并更新如下所示的文本,因此每次新创建单元格时,它都会将先前输入的文本更新为textField。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

  var cell......

  cell.delegate = self
  cell.textField.text = textFieldText

 return cell
}

3.在单元委托方法实现中每次都更新文本,这里我们有一个参数单元,通过知道indexPath来确定当前单元格。

func textFieldText(cell: UITableViewCell, text: String) {
    let indexPath = tableView.indexPathForCell(cell)
    textFieldText = text
 }

答案 3 :(得分:-1)

@BencePattogato答案是正确的。

另一个解决方案是将单元格保存为本地属性,并且当表格视图尝试显示此单元格时,不再重复使用(重新创建)它:

private var yourLocalCell: first_cell?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

     // Do some additional check here if this is time to display first_cell

     if let cell = yourLocalCell {
         return cell
     }

     var cell = table_view_one.dequeueReusableCell(withIdentifier: "first_cell", for: indexPath) as! first_cell 
     if(indexPath.row>0)
     {
         cell.add_new_btn.setImage(UIImage(named:"close"), for: .normal)
     } 
     cell.delegate = self
     yourLocalCell = cell 
     return cell 
  }
相关问题