【问题标题】:Cannot downcast UIButton to a subclass无法将 UIButton 向下转换为子类
【发布时间】:2016-02-23 08:29:51
【问题描述】:

我四处寻找,无法弄清楚我做错了什么。我正在尝试将UIButton 向下转换为以下代码行中的子类:

var currentButton: FileButton = UIButton(type: .System) as! FileButton

FileButtonUIButton 的一个简单子类,它只使用按钮存储几个变量。代码如下:

import UIKit

class FileButton: UIButton {

     var fileAddress: String = ""
     var fileMsgId: String = ""
     var fileAppId: String = ""

}

当我尝试执行此代码时,我在控制台中收到以下错误:

无法将“UIButton”类型的值 (0x19e9c9e40) 转换为 'CollectionFun.FileButton' (0x100127490)。

有什么想法吗?这似乎应该很简单,但我无法弄清楚。谢谢。

【问题讨论】:

    标签: ios swift cocoa-touch uibutton


    【解决方案1】:

    与其他面向对象的语言一样,如果您将变量初始化为超类(在您的情况下为 UIButton),则不能将其向下转换为子类(在您的情况下为 FileButton)。这是因为您正在初始化一个UIButton 对象,它不是FileButton。只需更改代码以初始化 FileButton 对象,它应该可以工作。

    因此,您应该将UIButton(type: .System) as! FileButton 替换为FileButton(type: .System)。请注意,现在不需要强制转换,因为我们直接初始化 FileButton 对象。

    【讨论】:

    • 谢谢您(和其他响应者)。这行得通。我不知道你可以在子类上使用超类初始化器。
    • 如果答案对您有所帮助,如果您可以将其标记为已接受,那就太好了(单击答案旁边的勾号)。它会帮助其他有同样问题的人。
    • 完成!感谢您的提示 - 我是 stackoverflow 的新手,用户界面仍然很混乱。
    【解决方案2】:

    您不能在您的示例中向下转换对象。您创建UIButton 类型对象并尝试将其转换为不是它的父对象或继承层次结构更高的其他对象,在这种情况下,新对象具有更多功能并且需要分配更多内存。你可以像这样编译你的代码没有错误:

    var currentButton = UIButton(type: .System) as? FileButton
    

    但这将是无用的代码,因为它总是会返回nil

    为了解释更清楚,举个例子。你可以这样做:

    var button1 = FileButton()
    button1.fileAddress = "qwerty"
    var button2 = button1 as UIButton
    var button3 = button2 as? FileButton
    print(button3.fileAddress)
    

    print 将是

    可选的(“qwerty”)

    它会起作用,因为第一个对象是FileButton 类型。

    但是这段代码:

    var button1 = UIButton()
    var button2 = button1 as? FileButton
    print(button2?.fileAddress)
    

    将打印

    你试着像第二个例子那样做

    【讨论】:

      【解决方案3】:

      只需调用:

      var currentButton: FileButton = FileButton(type: .System)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-04
        • 2021-11-23
        • 1970-01-01
        相关资源
        最近更新 更多