UITableView - “无法将类型'UITableViewCell'的值转换为AppName.CustomCell”

时间:2018-02-01 19:47:20

标签: ios swift uitableview

当我尝试打开表格视图时,我在控制台中收到此错误:

  

“无法将'UITableViewCell'类型的值转换为       'AppName.NameTableViewCell'。“

值得注意的几点:

  1. 我没有使用故事板
  2. 我已将我的单元格注册到viewDidLoad()
  3. 中的tableView

    以下是一些澄清的截图。

    let tableView = UITableView()
    override func viewDidLoad() {
        tableView.register(NameTableViewCell.self, forCellReuseIdentifier: "cellName")
        ...
    }
    
    ...
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = UITableViewCell(style: .default, reuseIdentifier: "cellName") as! NameTableViewCell
            cell.textCell.text = self.menuText[indexPath.row]
            return cell
        }
    }
    

3 个答案:

答案 0 :(得分:0)

您'重新尝试将UITableViewCell转换为NameTableViewCell

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

    if(indexPath.row == 0)
    {
      let cell = tableView.dequeueReusableCell(withIdentifier:"cellName1") as! NameTableViewCell1
      return cell
    }
   else
     if(indexPath.row == 1)
     {
       let cell = tableView.dequeueReusableCell(withIdentifier:"cellName2") as! NameTableViewCell2
       return cell
     }

  }

答案 1 :(得分:0)

我已经通过检查目标部分中的单元格类解决了此问题。它被错过了。

答案 2 :(得分:-1)

您需要更改代码,以便您注册的单元格类实际上正在cellForRow方法中使用。试试这个:

func viewDidLoad() {
    tableView.register(NameTableViewCell.self, forCellReuseIdentifier: "cellName")
    tableView.register(OtherTableViewCell.self, forCellReuseIdentifier: "otherName")
    tableView.register(ThirdTableViewCell.self, forCellReuseIdentifier: "thirdName")
}

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

    if indexPath.row == 0 {
      let cell = tableView.dequeueReusableCell(withIdentifier: "cellName", for: indexPath) as! NameTableViewCell
      // your cell setup code here
      return cell
    } else if indexPath.row == 1 {
       let cell = tableView.dequeueReusableCell(withIdentifier: "otherName", for: indexPath) as! OtherTableViewCell
      return cell
    } else if indexPath.row == 2 {
       let cell = tableView.dequeueReusableCell(withIdentifier: "thirdName", for: indexPath) as! ThirdTableViewCell
      return cell
    }
}
相关问题