使用 UITextField 在 tableview 末尾添加行

Use UITextField to add row at end of tableview

我有一个包含 2 个部分的 UITableView,第一个部分有单元格,每个单元格代表数组中的不同项目,第二个部分调用带有文本字段的 UIAlertController。我希望我在文本字段中写的任何内容都显示在 tableView 的第一部分中。我的代码目前是:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    switch indexPath.section {
    case 0:
        tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark

        UserDefaults.standard.set(selectedCaseSolutionsForCell[indexPath.row], forKey: "ollShowAlg\(selectedCaseID)")
        print("OLL Case with ID \(selectedCaseID) had its main algorithm changed to \(selectedCaseSolutionsForCell[indexPath.row])")
        let newMainSolve : String = UserDefaults.standard.string(forKey: "ollShowAlg\(selectedCaseID)")!
        print("THE ALGORITHM IS NOW \(newMainSolve)")


    case 1:
        tableView.cellForRow(at: indexPath)?.accessoryType = .none
        let alert = UIAlertController(title: "Add New Algoritm", message: "", preferredStyle: .alert)
        alert.addTextField()
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
            let textField = alert?.textFields![0] // Force unwrapping because we know it exists.
            print("Text field: \(textField!.text!)")

        }))
        present(alert, animated: true)

    default:
        return
    }      
}

如何将文本字段输入添加到数组,然后在 UITableView 的末尾显示?这个问题不是重复的,因为我没有使用自定义单元格,也没有 IBOutlet 或 IBAction。

我假设 table 的数据源是一个名为 data 的字符串数组。像这样:

fileprivate var data: [String] = []

那么在这一行 print("Text field: \(textField!.text!)") 之后你所要做的就是添加以下内容:

self.table.beginUpdates()
self.data.append(textField!.text!)
self.table.insertRows(at: [IndexPath(item: self.data.count - 1, section: 0)], with: .bottom)
self.table.endUpdates()