【问题标题】:" Could not cast value of type 'UITableViewCell'...to 'UILabel' "“无法将‘UITableViewCell’类型的值转换为‘UILabel’”
【发布时间】:2016-10-28 15:19:41
【问题描述】:

这是我遇到的错误。我确信这是一个简单的修复,但我遇到了一些麻烦。我更新了这个线程来添加代码。

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return 5
}


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

    let cell = tableView.dequeueReusableCell(withIdentifier: "CheckListItem", for: indexPath)

    let label = cell.viewWithTag(1000) as! UILabel

    switch indexPath.row {
    case 0:
        label.text = "Walk the dog"
    case 1:
        label.text = "Brush my teeth"
    case 2:
        label.text = "Learn iOS development"
    case 3:
        label.text = "Soccer practice"
    case 4:
        label.text = "Eat ice cream"
    default:
        label.text = "Nothing"
    }
    return cell
}

【问题讨论】:

  • 你是在标签还是单元格上设置了标签?此外,您真的不应该使用标签。子类化您的单元格,并在标签和单元格子类上的属性之间设置一个出口。
  • 请不要将代码发布为图像。请将相关代码作为文本复制并粘贴到您的问题中。它使回答时更容易阅读和参考。
  • 谢谢。我必须在标签上设置标签,而不是单元格。

标签: ios swift uilabel


【解决方案1】:

这就是viewWithTag(_:) 函数的作用:

返回视图最近的后代(包括它自己) 特定标签,如果没有子视图具有该标签,则为 nil。

所以你得到的是对象本身以及它最近的后代。看起来您只是想在单元格内设置文本,所以您只需将代码更改为:

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "CheckListItem", for: indexPath)

    switch indexPath.row {
    case 0:
        cell.textLabel.text = "Walk the dog"
    case 1:
        cell.textLabel.text = "Brush my teeth"
    case 2:
        cell.textLabel.text = "Learn iOS development"
    case 3:
        cell.textLabel.text = "Soccer practice"
    case 4:
        cell.textLabel.text = "Eat ice cream"
    default:
        cell.textLabel.text = "Nothing"
    }
    return cell
}

【讨论】:

    【解决方案2】:

    我正在学习 iOS Apprentice 系列,遇到了和你一样的问题。

    我认为您可能想检查在 Main.storyboard 中将 tag:1000 附加到的位置 - 如果您因为这个原因而失败,您可能已将标签附加到 UITableViewCell 而不是 Label (类型UILabel) 在内容视图下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-30
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多