我的应用程序有问题。我有一个表格 View ,其中每个单元格都包含一个文本字段。当我在其中写入并向下滚动,而不是向上滚动时,我在其中写入的数据消失了。
这些是我在 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:)
会再次被调用。在该方法中,每次调用时都会增加计数,因此它不会使用第一个条件,而是转到设置 cell.TextField.text = ""
的第二个条件语句,因为计数可能大于 arrayOfNames.count
。你用 count
做什么?也许重新考虑如何更好地编写该部分的代码。
关于ios - 当我滚动 TableView 时,UItextField 数据消失了——Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41707112/