如何将标签文本添加到tableViewCell

问题描述 投票:-7回答:1

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

ios swift uitableview uilabel
1个回答
-1
投票

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

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 dataSource方法:

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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.