我的应用程序出现问题。我有一个表格视图,其中每个单元格都包含一个文本字段。当我在其中写下并向下滚动,而不是向上滚动时,我在其中写入的数据就会消失。
这些是我在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
}
}
如您所见,我将文本字段中的所有书面文本保存到数组中。任何帮助,将不胜感激。
提前致谢
答案 0 :(得分:3)
向后滚动tableView(tableView: cellForRowAt:)
时会再次调用。在该方法中,每次调用时都会增加计数,因此不会使用第一个条件,而是转到设置cell.TextField.text = ""
的第二个条件语句,因为count可能大于arrayOfNames.count
。你在使用count
做什么用途?也许重新考虑如何更好地编写这部分代码。
答案 1 :(得分:1)
重建您的单元格。所以你失去了他们。您可以使用方法PrepareForReuse
在重新创建文本时将其设置回来。