ios - 当我滚动 TableView 时,UItextField 数据消失了——Swift

标签 ios swift

我的应用程序有问题。我有一个表格 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/

相关文章:

ios - 如何将cocos2d-x 3.1模板获取到XCode 5.x中?

ios - 函数 didReceive RemoteMessage 未被调用 Swift 5

swift - 使用 DateComponents 创建日期

swift - 对常量使用明确定义的类型有什么好处

html - CSS 中的@viewport 标签在 iOS 上不起作用

ios - UICollectionView contentOffset 在键盘出现时发生变化

ios - 如何在 ios 中使用 XMPP 和 openfire 服务器传输文件?

iphone - 将 Plist 读入 UITableView 时遇到问题

ios - 什么是 UserNotification 框架相当于 didReceive 通知 : UILocalNotification?

ios - 尝试为表格设置行数时 WatchKit 应用程序崩溃