Остановить tableView.reloadData (), выдавая ошибку? (Разрешено) - PullRequest
0 голосов
/ 03 ноября 2019

(Это было исправлено, спасибо за помощь!) Я следую учебному пособию для простого приложения со списком, в котором вы добавляете элементы в список через UITextField. Тем не менее, это происходит сбой в tableView.reloadData (), и я не знаю, почему. Если сделать tableView необязательным, это не приведет к сбою, но также заставит приложение не добавлять элемент в список. Вот код класса:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
    struct todo {
        var text: String
        var isDone: Bool
    }

    var todos = [todo]()
    @IBOutlet var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        todos.append(todo(text: "test", isDone: false))
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return todos.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "todo-cell", for: indexPath)
        let todo = todos[indexPath.row]
        cell.textLabel?.text = todo.text
        if todo.isDone {
            cell.accessoryType = .checkmark
        } else {
            cell.accessoryType = .none
        }
        return cell
    }

    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: UITableView.RowAnimation.automatic)
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        todos.append(todo(text: textField.text!, isDone: false))
        tableView.reloadData() // Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value... crashes here!!
        textField.text = ""
        textField.resignFirstResponder()
        return true
    }
}

Ответы [ 2 ]

1 голос
/ 03 ноября 2019

объект tableView - ноль.

@IBOutlet var tableView: UITableView! // is not link with viewController
1 голос
/ 03 ноября 2019

Мое первое предположение состоит в том, что вы не связали просмотр таблицы в раскадровке с контроллером представления.

Возможно, вам следует сначала проверить это. Поместите точку останова в viewDidLoad, чтобы увидеть, установлена ​​ли ваша таблица. Если его ноль, то есть ваша проблема.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...