Получение ошибки «Неустранимая ошибка: индекс вне диапазона» при попытке настроить две ячейки в табличном представлении - PullRequest
1 голос
/ 09 октября 2019

Я получаю сообщение об ошибке «Неустранимая ошибка: индекс выходит за пределы диапазона», когда я настраиваю две ячейки в табличном представлении, ShareSomthingCell исправляется и показывает только один раз, но пост-ячейка повторяется согласно базе данных

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

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1 + posts.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.row == 0 {
            if let cell = tableView.dequeueReusableCell(withIdentifier: "ShareSomethingCell") as? DetailsCellInHomeScreen {
                if currentUserImageUrl != nil {
                   cell.configCell(userImgUrl: currentUserImageUrl)
                   cell.shareBtn.addTarget(self, action: #selector(toCreatePost), for: .touchUpInside)
                }
                return cell
            }
        }

        guard let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as? PostTableViewCell else { return UITableViewCell() }

        cell.btnComment.tag = indexPath.row
        cell.btnComment.addTarget(self, action: #selector(toComments(_:)), for: .touchUpInside)

        cell.favoritebutton.tag = indexPath.row
        cell.favoritebutton.addTarget(self, action: #selector(favupdate(_:)), for: .touchUpInside)
        cell.set(post: posts[indexPath.row - 1])
        return cell


        }

Я получаю сообщение об ошибке в этой строке

cell.set(post: posts[indexPath.row - 1])

Ответы [ 2 ]

1 голос
/ 09 октября 2019

Авария происходит, если есть ошибка дизайна относительно первой ячейки.

Не guard ячейки, принудительно распаковывайте их всегда. Если происходит сбой, идентификатор неверен или класс не задан, но это можно исправить немедленно.

Этот код не должен вызывать исключение за пределами допустимого диапазона.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ShareSomethingCell" for: indexPath) as! ScoresCellInHomeScreen 
        if let imageURL = currentUserImageUrl {
           cell.configCell(userImgUrl: imageURL)
           cell.shareBtn.addTarget(self, action: #selector(toCreatePost), for: .touchUpInside)
        }
        return cell            
    }

    let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell

    cell.btnComment.tag = indexPath.row
    cell.btnComment.addTarget(self, action: #selector(toComments(_:)), for: .touchUpInside)

    cell.favoritebutton.tag = indexPath.row
    cell.favoritebutton.addTarget(self, action: #selector(favupdate(_:)), for: .touchUpInside)
    cell.set(post: posts[indexPath.row - 1])
    return cell
}
0 голосов
/ 10 октября 2019

Если у вас "postCell" в качестве первой ячейки (indexpath.row == 0), приложение будет аварийно завершено.

В приведенном выше сценарии управление переходит к первому оператору if (if indexPath.row == 0), но сбрасывает второе if (if let cell = tableView.dequeueReusableCell(withIdentifier: "ShareSomethingCell"))

и контроль в конечном итоге приходит к cell.set(post: posts[indexPath.row - 1]), и как indexpath.row == 0 ваш код пытается получить доступ к posts[-1], что приводит к сбою

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