从自定义UITableViewCells读取编辑的UITextFields

时间:2019-06-14 15:16:06

标签: ios swift uitableview

我有一个以listView形式呈现给用户进行编辑的项目列表。列表编辑完成后,我想将编辑后的列表存储回数组中。

我有一个循环读取每个项目,但是它带有一个空单元格列表。我假设我没有正确识别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 = [“,”,“,”,“,”,“,”,“,”,“,”,“,”,“,”,“,”,“,”,“” ,“”]

1 个答案:

答案 0 :(得分:0)

您需要使用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!)
    }
}

OR

(tableView.visibleCells as! [A8EditorTableViewCell]).forEach { 
  tChoices.append($0.listItem.text!)
} 
  

如果不是这种情况,则假定表的所有单元格都是可见的

相关问题