点击addButton时如何在tableViewCell中显示UILabel的文本内容
实现方案
你现有的代码已经完成了数据源存储、TableView 基础代理配置的核心逻辑,唯一缺失的是数据源更新后触发 TableView 刷新的步骤,系统不会自动感知数组内容变化更新 UI,需要手动调用刷新方法,同时建议增加可选值安全判断避免强制解包崩溃。
具体修改点
- 在
addButton方法中完成数组数据追加后,调用 TableView 刷新方法 - 对
amountLabel.text做非空判断,避免空值强制解包引发崩溃
完整修改后代码
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return amountLabelArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = amountLabelArray[indexPath.row] return cell } @IBOutlet weak var amountLabel: UILabel! @IBOutlet weak var tableView: UITableView! var amountLabelArray = [String]() override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self // 可选配置:提前注册cell,避免运行时找不到标识的问题 tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") } @IBAction func oneButton(_ sender: Any) { let number = 1 amountLabel.text = (amountLabel.text ?? "") + String(number) } // 该方法用于将金额添加到tableViewCell中 @IBAction func addButton(_ sender: Any) { guard let text = amountLabel.text, !text.isEmpty else { return } amountLabelArray.append(text) print("This is the array \(amountLabelArray)") amountLabel.text = "" // 刷新列表 tableView.reloadData() } }
可选优化:局部刷新提升性能
如果不需要全局刷新整个列表,只想为新增的行添加插入动画,可以用局部刷新代替全局reloadData,修改addButton方法即可:
@IBAction func addButton(_ sender: Any) { guard let text = amountLabel.text, !text.isEmpty else { return } amountLabelArray.append(text) // 计算新增行的位置 let newIndexPath = IndexPath(row: amountLabelArray.count - 1, section: 0) // 局部插入行,带动画效果 tableView.insertRows(at: [newIndexPath], with: .automatic) amountLabel.text = "" }
内容的提问来源于stack exchange,提问作者user14908036
相关产品推荐
相关产品推荐

