func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "CollectionDetailsItem", for: indexPath) as? CharacterCollectionDetailsTableCell else {
        fatalError("Dequeued cell is not an instance of CharacterDetailsTableViewCell class.")
    }
    return cell
}

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "CollectionDetailsItem", for: indexPath) as? CharacterCollectionDetailsTableCell else {
        fatalError("Dequeued cell is not an instance of CharacterDetailsTableViewCell class.")
    }
    if let character = character {
        cell.setCollectionViewDataSourceDelegate(dataType: dataTypes[indexPath.row], characterEntity: character)
    }
}

我真的不明白为什么会发生此错误,有人可以帮我做错什么吗?

最佳答案

由于错误地实现了tableview的数据源和委托方法,因此您将获得错误。 dequeueReusableCell用于在tableview中创建可重用的单元格。因此,应在tableview的cellForRow dataSource方法中实现。您在第一种方法中做的很好,但这是您做错了的地方。

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "CollectionDetailsItem", for: indexPath) as? CharacterCollectionDetailsTableCell else {
        fatalError("Dequeued cell is not an instance of CharacterDetailsTableViewCell class.")
    }
    if let character = character {
        cell.setCollectionViewDataSourceDelegate(dataType: dataTypes[indexPath.row], characterEntity: character)
    }
}

此方法不是您可以创建单元格的地方,而是可以根据需要在显示单元格时执行各种任务。因此,根据您的要求,可能会是这样。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "CollectionDetailsItem", for: indexPath) as? CharacterCollectionDetailsTableCell else {
        fatalError("Dequeued cell is not an instance of CharacterDetailsTableViewCell class.")
    }
    return cell
}

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if let cell = cell as? CharacterCollectionDetailsTableCell {
        guard let character = character else {
            return
        }
        cell.setCollectionViewDataSourceDelegate(dataType: dataTypes[indexPath.row], characterEntity: character)
    }
}

谢谢。

关于ios - 尝试使同一索引路径的多个单元出队,这是不允许的。错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49411653/

10-11 04:27
查看更多