【问题标题】:how to add label text to tableViewCell如何将标签文本添加到 tableViewCell
【发布时间】:2019-07-16 23:57:09
【问题描述】:

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

【问题讨论】:

    标签: ios swift uitableview uilabel


    【解决方案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)
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 2021-07-11
      • 2016-05-25
      • 1970-01-01
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多