首页 > 解决方案 > 如何将标签文本添加到 tableViewCell

问题描述

我正在练习创建一个应用程序,其中有一个标签,当用户按下按钮时,该标签会从 UITextField 获取其文本。现在,我添加了另一个按钮和一个表格视图,我希望能够使用与秒表圈相同的机制将标签的文本“保存”到表格单元格中。所以,为了清楚起见,我希望按钮在每次按下时将标签的文本传输到表格视图单元格。

标签: iosswiftuitableviewuilabel

解决方案


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

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)
    }
}

tableViewdataSource 方法中:

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
    }
}

推荐阅读