滚动tableview时复制数据查看

问题描述:

我有自定义UITableViewCell其中包含文本字段。问题出现在我在第一个文本字段中输入一些文本后(例如)在滚动tableView后,此文本在另一个单元格中复制。我知道,这是因为tableView出队单元。
处理这个问题的正确方法是什么?
我的代码:
滚动tableview时复制数据查看

@IBOutlet weak var tableView: UITableView! 

     var dataArray: [String] = [] 

     override func viewDidLoad() { 
     super.viewDidLoad() 

     tableView.dataSource = self 

     for i in 0...50 { 
      dataArray.append("Elemnt # \(i)") 
     } 
     } 
    } 

    extension ViewController: UITableViewDataSource { 
     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return dataArray.count 
     } 

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "cell") 
     return cell 

    } 

你出列的单元格中的-tableView:cellForRowAtIndexPath:方法后立刻就可以访问它关联的文本字段,并清除它。

或者,如果您有子类UITableViewCell,则可以覆盖子类中的prepareForReuse()方法并执行相同的操作。

+0

谢谢。我会尝试你的解决方案 – makedonskii

1。需要创建一个单独的阵列与初始textValue:

var stringArray:[String] = ["", "", "", ""] 
  1. 分配值中的cellForRowAtIndexPath

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") 
    
    cell.textfield.text = stringArray[indexpath.row] // change your swift syntax 
    
  2. 3至文本框。在textFieldDidEndEditing中替换该初始值。

    func textFieldDidEndEditing(_ textField: UITextField) { 
          let buttonPosition:CGPoint = textField.convert(CGPointZero, 
          to:self.tableView) 
          let indexPath = self.tableView.indexPathForRow(at: buttonPosition) 
          stringArray[indexPath.row] = textField.text 
          println(allCellsText) 
          self.tableView.reloadData() // or you can reload specific cell 
         } 
        } 
    
开始=>
+0

这个工作吗? – KKRocks