如何将标签文本添加到 tableViewCell

how to add label text to tableViewCell

我正在练习创建一个应用程序,其中我有一个标签,当用户按下按钮时,该标签会从 UITextField 获取文本。现在,我添加了另一个按钮和一个 table 视图,并且我希望能够将标签的文本 "save" 添加到 table 具有相同机制的秒表圈数的单元格中。 因此,需要明确的是,我希望每次按下按钮时都能将标签的文本传输到 table 视图单元格。

保存按钮后,您需要将文本存储在某处并重新加载 table。 (或插入动画)

class ViewController: UIViewController {
    @IBOutlet private var textField: UITextField!
    @IBOutlet private var tableView: UITableView!
    var texts: [String] = [] {
        didSet { tableView.reloadData() }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "SimpleCell")
        tableView.dataSource = self
    }

    @IBAction func saveButtonTapped(_ sender: UIButton) {
        guard let newText = textField.text else { return }
        self.texts.append(newText)
    }
}

并且在 tableView 数据源方法中:

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return texts.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SimpleCell", for: indexPath)!
        cell.textLabel?.text = texts[indexPath.row]
        return cell
    }
}