我以 tableView 的形式向用户展示了可供编辑的项目列表。编辑列表后,我想将编辑后的列表存储回数组中。
我有一个循环来读取每个项目,但它出现了一个空的单元格列表。我假设我没有正确识别indexPath。任何帮助将不胜感激。
// This establishes the tableView correctly
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:
"cell1", for: indexPath) as! a8EditorTableViewCell
cell.listItem?.text = popChoices[indexPath.row]
return cell
// Action attempts to save the edited data, but produces
tChoices = []
@IBAction func save(_ sender: Any) {
var tChoices: [String] = []
//IndexPath.row.forEach {
let n = popChoices.count // ok
print("save, n=",n)
for index in (0...n) {
let indexPath = IndexPath(row:index, section:0)
let cell = tableView.dequeueReusableCell(withIdentifier:
"cell1", for: indexPath) as! a8EditorTableViewCell
tChoices.append(cell.listItem.text!)
print("n=",n,"tchoice=",cell.listItem.text!) // < prints
blanks
}
print("tchoices=",tChoices)
print("popChoices before change=",popChoices)
popChoices = tChoices
onChg?(popChoice) // need to change to array
print("popChoiceA=",popChoice)
dismiss(animated: true)
}
结果如下所示。应该是 15 个字符串。
tchoices= ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]
最佳答案
您需要使用cellForRowAt
而不是dequeueReusableCell
(0..<n).forEach {
let indexPath = IndexPath(row:$0, section:0)
if let cell = tableView.cellForRow(at:indexPath) as? A8EditorTableViewCell {
tChoices.append(cell.listItem.text!)
}
}
或
(tableView.visibleCells as! [A8EditorTableViewCell]).forEach {
tChoices.append($0.listItem.text!)
}
This assumes all cells of the table are visible if it's no the case you need to go with another way
关于ios - 从自定义 UITableViewCell 读取编辑后的 UITextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56601038/