首页 > 解决方案 > 我无法保存用户输入并将其添加到 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)

    }
}

标签: iosswiftinputtableviewtextfield

解决方案


查看您的代码,假设这就是全部,您没有在任何地方分配代表。在viewDidLoad()你必须设置你的 UITableViewDelegate、UITableViewDataSource 和 UITextFieldDelegate。

tableView.delegate = self
tabelView.dataSource = self
textField.delegate = self

推荐阅读