ios - 如何将标签文本添加到 tableViewCell
问题描述
我正在练习创建一个应用程序,其中有一个标签,当用户按下按钮时,该标签会从 UITextField 获取其文本。现在,我添加了另一个按钮和一个表格视图,我希望能够使用与秒表圈相同的机制将标签的文本“保存”到表格单元格中。所以,为了清楚起见,我希望按钮在每次按下时将标签的文本传输到表格视图单元格。
解决方案
在保存按钮之后,您需要将文本存储在某处并重新加载表格。(或者用动画插入)
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
}
}
推荐阅读
- python - 将 IBM Cloudant 与 SQLAlchemy 结合使用
- java - 如何在 android studio 上为 Android Apk 文件生成 SHA512 校验和
- windows - .Net Core windows 身份验证,并在应用程序数据库中进行一些额外检查
- c++ - 跨解决方案项目共享 C++ 源文件以供模板使用
- jsf - javax.faces.webapp.FacesServlet 不能分配给 javax.servlet.Servlet , jakarta.servlet.Servlet
- nlp - 您如何确保节 CoreNLPClient 的可行端点?
- ruby-on-rails - Rails delay_job 要求不存在的文件
- node.js - 每次调用时出现 AWS Lambda 错误 EADDRINUSE
- angular - 如何在不使用 __zone_symbol__value 属性的情况下从 localStorage 检索值
- java - 用杰克逊注解“内联”一个对象