Swift - 当 uitableview 重用单元格时用户输入混淆了? [英] Swift - User input mixed up when uitableview reuses cells?

查看:26
本文介绍了Swift - 当 uitableview 重用单元格时用户输入混淆了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发具有 UITableView 的应用程序,其中包含包含 UITextField 的自定义单元格.我遇到的问题是,在用户向文本字段输入数字后,滚动时,tableView 会重用该单元格,并且用户之前的输入在新单元格中初始化.例如,如果我将数字 7 放在顶部单元格的文本字段中,当我滚动时,最新的单元格中已经包含 7.我想知道如何解决这个问题?感谢您的帮助.

I am currently developing an app that features a UITableView with custom cells that contain a UITextField. The problem I am having is that, after the user inputs a number to the textfield, upon scrolling, the tableView reuses that cell and the user's previous input is initialized in the new cell. For example, if I put the number 7 in the top cell's textfield, when I scroll, the newest cell already has a 7 in it. I am wondering how I can fix this problem? Thank you for any help.

由于我的问题不清楚,我基本上需要一种方法让我的 UITableViewCell 与我的 UITableViewController 中的模型对话",以便当用户完成编辑单元格中的 UITextField 时,我可以将输入保存到我的视图控制器中的数组.再次感谢

Since my problem is unclear, I basically need a way for my UITableViewCell to "talk" to the model in my UITableViewController so that when the user is done editing the UITextField in the cell, I can save the input to an array in my view controller. Thanks again

推荐答案

快速解决方法是创建一个整数数组来表示表中的数字.然后,在 cellForRowAtIndexPath 方法中,只需执行类似

The quick fix is to create an array of integers to represent numbers in the table. Then, in cellForRowAtIndexPath method, just do something like

cell.textField.text = numberArray[indexPath.row]

您现在需要将文本字段数据实际保存到此数组中,使用相同的方法添加

You need to actually save the text fields data into this array now though, in the same method add

cell.textField.addTarget(self, action: "onTextChanged:", forControlEvents: UIControlEvents.EditingChanged)

创建 ,,onTextChanged'' 方法,如

Create the ,,onTextChanged'' method like

func onTextChanged(sender: UITextField) {
    let cell = sender.superview! as! UITableViewCell
    let indexPath = self.tableView.indexPathForCell(cell)!
    numberArray[indexPath.row] = sender.text.toInt()!
}

这篇关于Swift - 当 uitableview 重用单元格时用户输入混淆了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆