ios - 我无法保存用户输入并将其添加到 textFieldShouldRetrun 函数中的表到 Xcode 中的表中,我不知道为什么
问题描述
多年来,我一直在尝试让用户的输入保存并添加到表格中,以便它可以用作待办事项列表,但我无法做到。我试过在这里搜索,但没有任何帮助。这是我的整个代码。这实际上是我第一次使用 Xcode 和 Swift,所以我可能遗漏了一些明显的错误。问题出在 textFieldShouldReturn 函数的开头(对不起,我没有解释清楚!)
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return todos.count
}
struct todo {
var text: String
var isDone: Bool
}
// this is the problem area:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let t = todo(text: textField.text!, isDone: false)
todos.append(t)
tableView.reloadData()
textField.text = ""
textField.resignFirstResponder()
return true
}
var todos = [todo]()
@IBOutlet weak var tableView: UITableView!
// the rest
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
var todo = todos[indexPath.row]
todo.isDone = !todo.isDone
todos[indexPath.row] = todo
tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let id = "todo-cell"
let cell = tableView.dequeueReusableCell(withIdentifier: id, for: indexPath)
let todo = todos[indexPath.row]
cell.textLabel?.text = todo.text
if todo.isDone {
cell.accessoryType = .checkmark
}else{
cell.accessoryType = .none
}
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
let t = todo (text:"clean my room", isDone: false)
todos.append(t)
}
}
解决方案
查看您的代码,假设这就是全部,您没有在任何地方分配代表。在viewDidLoad()
你必须设置你的 UITableViewDelegate、UITableViewDataSource 和 UITextFieldDelegate。
tableView.delegate = self
tabelView.dataSource = self
textField.delegate = self
推荐阅读
- r - 如何从列表中的第 n 个向量中选择多个元素?
- flutter - 如何在 Win32 中创建颤振窗口之前添加启动画面
- flutter - Flutter 应用程序上的辅助功能扫描仪总是说没有可读标签问题?
- bar-chart - 如果 Google Data Studio 条形图过滤器使我的图例变得杂乱无章,我该怎么办?
- reactjs - 打字稿抱怨函数参数类型
- php - WooCommerce 自定义条件函数在产品更新时引发严重错误
- django - Django:每次 git 推送到服务器后,Git 忽略的文件都会自动删除
- android - Android Espresso - 等到显示对话框
- reactjs - 使用 react 和 chart js 显示字典数组
- c# - 不是 url 时使用多个命名空间的 XML 选择