我正在创建一个应用程序,我需要用户在 UITableViewCell
中填写一些输入,有点像表单。当用户点击完成按钮时,我需要收集这些输入,以便我可以运行一些计算并将它们输出到另一个 View Controller 上
这是我用来收集这些输入的方法:
func doneButtonTapped() {
var dict = [String: Any]()
for rows in 0...TableViewCells.getTableViewCell(ceilingType: node.ceilingSelected, moduleType: node.moduleSelected).count {
let ip = IndexPath(row: rows, section: 0)
let cells = tableView.cellForRow(at: ip)
if let numericCell = cells as? NumericInputTableViewCell {
if let text = numericCell.userInputTextField.text {
dict[numericCell.numericTitleLabel.text!] = text
}
} else if let booleanCell = cells as? BooleanInputTableViewCell {
let booleanSelection = booleanCell.booleanToggleSwitch.isOn
dict[booleanCell.booleanTitleLabel.text!] = booleanSelection
}
}
let calculator = Calculator(userInputDictionary: dict, ceiling_type: node.ceilingSelected)
}
我遇到的问题是当单元格不在 View 中时,用户的输入会从内存中清除。这里有两个截图来说明我的观点:
如您所见,当所有单元格都出现时,完成按钮设法存储了来自用户的所有输入,显然来自控制台打印。但是,如果单元格不在视野范围内,则 area/m2 的输入将设置为 nil:
我想到的解决方案是我不应该使用可出列的单元格,因为我确实希望单元格在不可见时保留在内存中,但许多 stackover 社区强烈反对这种做法。我应该如何解决这个问题?谢谢!
更新
cellForRow(at: IndexPath)
的代码
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let node = node else {
return UITableViewCell()
}
let cellArray = TableViewCells.getTableViewCell(ceilingType: node.ceilingSelected, moduleType: node.moduleSelected)
switch cellArray[indexPath.row].cellType {
case .numericInput :
let cell = tableView.dequeueReusableCell(withIdentifier: "numericCell", for: indexPath) as! NumericInputTableViewCell
cell.numericTitleLabel.text = cellArray[indexPath.row].title
return cell
case .booleanInput :
let cell = tableView.dequeueReusableCell(withIdentifier: "booleanCell", for: indexPath) as! BooleanInputTableViewCell
cell.booleanTitleLabel.text = cellArray[indexPath.row].title
return cell
}
}
}
我的两个自定义单元格
NumericInputTableViewCell
class NumericInputTableViewCell: UITableViewCell {
@IBOutlet weak var numericTitleLabel: UILabel!
@IBOutlet weak var userInputTextField: UITextField!
}
BooleanInputTableViewCell
class BooleanInputTableViewCell: UITableViewCell {
@IBOutlet weak var booleanTitleLabel: UILabel!
@IBOutlet weak var booleanToggleSwitch: UISwitch!
}
有人要吗?
最佳答案
我同意其他贡献者的观点。这些单元不应用于数据存储。您应该考虑另一种方法(如 HMHero 建议的方法)。
但是,由于您的问题也是关于如何在删除 UITableViewCell 之前访问它,因此 UITableViewDelegate 中有一个方法可以用于此目的:
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// do something with the cell before it gets deallocated
}
此方法告诉代理指定的单元格已从表中删除。因此,它提供了在该细胞消失之前对其进行处理的最后机会。
关于ios - 如何在出队前保留 UITableViewCell 中的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46349740/