【问题标题】:Cast from "UITableViewCell" to unrelated type "UIView" always fails iOS9从“UITableViewCell”转换为不相关类型“UIView”总是失败iOS9
【发布时间】:2015-10-06 09:11:18
【问题描述】:

更新到 iOS9 后,我开始在以下代码中看到一个奇怪的警告:

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
    var result: UIView?

    if UserPerspective.List == currentUser.perspective.value
    {
        result = tableView.dequeueReusableCellWithIdentifier("CustomHeader") as? UIView
    }

    return result
}

如标题中所述,我收到以下警告:

从“UITableViewCell”转换为不相关类型“UIView”总是失败

我不明白为什么它会失败,因为 UITableViewCell 是 UIView 的子类,那么演员应该没问题。然而 swift 编译器不这么认为:)

【问题讨论】:

  • 我想没有必要将 UIView 子类转换为 UIView。
  • 您要从 UITableViewCell 投射?到 UIView,那确实总是会失败。你可以投射到 UIView 吗? - 那么它总是会成功。所以最好的选择是根本不施放——一切都会如你所愿。

标签: ios swift casting ios9


【解决方案1】:

你不应该施放它。

应该够了

let result = tableView.dequeueReusableCellWithIdentifier("CustomHeader")

结果是UITableViewCell?

如果你有一个自定义的 UITableViewCell,我们称之为customTableViewCell,你可以这样做:

let result = tableView.dequeueReusableCellWithIdentifier("CustomHeader") as! customTableViewCell

【讨论】:

  • 是的,我正试图上调——你有没有像我现在一样感到愚蠢:)
【解决方案2】:

您不需要将 UITableViewCell 转换为 UIView,因为它总是会成功,您会收到上述错误,因为您将一个可选项转换为 UIView

result = tableView.dequeueReusableCellWithIdentifier("CustomHeader")! as? UIView

这会起作用,但是投射它没有用。

【讨论】:

  • 这样我会得到另一个错误,该错误总是会成功。请参阅@William 的正确答案。
  • 是的,我在上面提到过。它总是会成功,所以你不需要铸造
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-09
  • 2015-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多