ios - 从自定义 UITableViewCell 读取编辑后的 ​​UITextField

标签 ios swift uitableview

我以 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/

相关文章:

swift - 代码。添加到测试目标的图像资源不会复制到测试包中

ios - 用 Collection View 替换所有 TableView 是好习惯吗?

ios - 嵌入在容器 View 中的 tableView 顶部的空白

swift - 在键入时关闭 Xcode 的未使用变量警告

iPhone View 分层

ios - 如何检查 AnyObject 单元格的类型?

iphone - UITableView 无法从数组中获取数据

ios - 快速 iOS : create UIDocument in app documents folder

swift - searchBar过滤的tableViewCells didSelectItemAt indexPath显示在navigationBar标题中

ios - Swift:执行函数作为参数