首页 > 解决方案 > 视图控制器中的多个 uitableview 给出错误

问题描述

我对以下在视图控制器中管理两个 uitableview 的代码有疑问。当在“directionTableView”中的模态控制器中插入数据时,会出现以下错误:

线程 1:信号 SIGABRT 'Could not cast value of type 'UITableViewCell' (0x1059e7560) to 'FoodTime.DirectionRecipeTableViewCell' (0x101388bf0). 2018-05-23 21:50:12.160281+0200 FoodTime[4577:360265] 无法将“UITableViewCell”(0x1059e7560)类型的值转换为“FoodTime.DirectionRecipeTableViewCell”(0x101388bf0)。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    var cell = UITableViewCell()
    if (tableView == self.ingredientTableView)
    {

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

        let ingredientCell = ingredients[indexPath.row]
        cell.textLabel?.text = ingredientCell.titleIngredientRecipe
        cell.detailTextLabel?.text = ingredientCell.subtitleIngredientRecipe
    }
    else if (tableView == self.directionTableView)
    {
        //Thread 1: signal SIGABRT on next line
        let cell = tableView.dequeueReusableCell(withIdentifier: "newDirectionCell", for: indexPath) as! DirectionRecipeTableViewCell                 
        let directionCell = directions[indexPath.row]
        cell.textLabel?.text = directionCell.directionSection
        cell.detailTextLabel?.text = directionCell.directionText
    }
    return cell
}

标签: iosswiftuitableview

解决方案


远离问题第一行

var cell = UITableViewCell()

实际上是 if 语句中返回的单元格是局部变量

所以试试这个

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

        if (tableView == self.ingredientTableView)
        {

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

            let ingredientCell = ingredients[indexPath.row]
            cell.textLabel?.text = ingredientCell.titleIngredientRecipe
            cell.detailTextLabel?.text = ingredientCell.subtitleIngredientRecipe

             return cell
        }
        else  
        {

            let cell = tableView.dequeueReusableCell(withIdentifier: "newDirectionCell", for: indexPath) as! DirectionRecipeTableViewCell //Thread 1: signal SIGABRT

            let directionCell = directions[indexPath.row]
            cell.textLabel?.text = directionCell.directionSection
            cell.detailTextLabel?.text = directionCell.directionText

            return cell
        }

}

还要确保使用相应的单元格注册每个表格视图


推荐阅读