当我滚动浏览TableView--Swift时,UItextField数据消失了



我的应用程序出现问题。我有一个表格视图,其中每个单元格都由一个文本字段组成。当我在其中写入并向下滚动,而不是向上滚动时,我在其中输入的数据就会消失。

以下是我在ViewController 中的一些功能

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UIScrollViewDelegate {
var arrayOfNames : [String] = [String]()
var rowBeingEdited : Int? = nil
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return initialNumberOfRows
}
var count: Int = 0;
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: TableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! TableViewCell

if(arrayOfNames.count > 0 && count < arrayOfNames.count) {
cell.TextField.text = self.arrayOfNames[indexPath.row]
}else{
cell.TextField.text = ""
}
count += 1

cell.TextField.tag = indexPath.row
cell.TextField.delegate = self
return cell
}
func textFieldDidEndEditing(_ textField: UITextField) {
let row = textField.tag
if row >= arrayOfNames.count {
for _ in ((arrayOfNames.count)..<row+1) {
arrayOfNames.append("") // this adds blank rows in case the user skips rows
}
}
arrayOfNames[row] = textField.text!
rowBeingEdited = nil
}
func textFieldDidBeginEditing(_ textField: UITextField) {
rowBeingEdited = textField.tag
}
}

正如您所看到的,我正在将文本字段中的所有书面文本保存到一个数组中。如有任何帮助,我们将不胜感激。

提前感谢

当您向上滚动时,tableView(tableView: cellForRowAt:)会再次被调用。在该方法中,每次调用时都要递增count,因此它不使用第一个条件,而是转到第二个条件语句,该语句将cell.TextField.text = ""设置为count可能大于arrayOfNames.count。你用count干什么?也许可以重新思考如何对该部分进行更好的编码。

您的单元格将被重新创建。所以你失去了他们。您可以使用方法PrepareForReuse在重新创建文本时将其设置回原处。

最新更新