Невозможно вставить строку в таблицу «Попытка вставить строку 0 в раздел 0, но после обновления есть только 0 разделов» - PullRequest
0 голосов
/ 05 мая 2019

Следуя этому руководству, https://www.hackingwithswift.com/read/5/overview

Я продолжаю получать эту ошибку, когда вставляю строку в верхнюю часть таблицы,

'NSInternalInconsistencyException', причина: 'попыткавставить строку 0 в раздел 0, но после обновления есть только 0 разделов '"

Вот код, который обрабатывает это.

func submit(_ answer: String) {
    let lowerAnswer = answer.lowercased()

    if isPossible(word: lowerAnswer) {
        if isOriginal(word: lowerAnswer) {
            if isReal(word: lowerAnswer) {
                usedwords.insert(answer, at: 0)

                //the below code is for animation even though we just inserted at index 0, the top of the table!

                let indexPath = IndexPath(row: 0, section: 0)

                tableView.insertRows(at: [indexPath], with: .automatic)


            }
        }
    }
}

Это должно позволять мнечтобы вставить данные из UIAlertController, заполните таблицу сверху.

Ниже мой ViewController

class ViewController: UITableViewController {
    var allwords = [String]()
    var usedwords = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        if let startWordsURL = Bundle.main.url(forResource: "start", withExtension: "txt") {
            if let startWords = try? String(contentsOf: startWordsURL) {
                allwords = startWords.components(separatedBy: "\n")
            }
        }
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(promptForAnswer))

        if allwords.isEmpty {
            allwords = ["silkworm"]
            }

        startGame()
    }

    func startGame() {
        title = allwords.randomElement()
        usedwords.removeAll(keepingCapacity: true)
        tableView.reloadData()
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return usedwords.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Word", for: indexPath)
        cell.textLabel?.text = usedwords[indexPath.row]
        return cell
    }

    @objc func promptForAnswer() {
        let ac = UIAlertController(title: "Enter Answer", message: nil, preferredStyle: .alert)
        ac.addTextField()

        let submitAction = UIAlertAction(title: "Submit", style: .default) {
            [weak self, weak ac] action in
            guard let answer = ac?.textFields?[0].text else {return}
            self?.submit(answer)
        }

        ac.addAction(submitAction)
        present(ac, animated: true)
    }

    func submit(_ answer: String) {
        let lowerAnswer = answer.lowercased()

        if isPossible(word: lowerAnswer) {
            if isOriginal(word: lowerAnswer) {
                if isReal(word: lowerAnswer) {
                    usedwords.insert(answer, at: 0)

                    //the below code is for animation even though we just inserted at index 0, the top of the table!

                    let indexPath = IndexPath(row: 0, section: 0)

                    tableView.insertRows(at: [indexPath], with: .automatic)
                }
            }
        }
    }

    func isPossible(word: String) -> Bool {
        return true
    }

    func isOriginal(word: String) -> Bool {
        return true
    }

    func isReal(word: String) -> Bool {
        return true
    }
}

1 Ответ

0 голосов
/ 06 мая 2019

Вы возвращаете usedWords.count для количества разделов, и вы не внедрили numberOfRowsInSection. Это означает, что в вашей таблице есть usedWords.count разделов, каждый из которых содержит 0 строк.

Вы сообщаете табличному представлению, что вставляете строку, но numberOfRowsInSection по-прежнему равно 0, поэтому вы получаете исключение.

Требуется один раздел с usedWords.count строками:

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) {
    return usedWords.count
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...