为什么我不能继承 SKSpriteNode

Why am I unable to subclass the SKSpriteNode

原谅我,我以前可能问过这个问题,但它以不同的方式打击了我,我仍在学习 Swift

在我的主场景中,我可以轻松地初始化一个节点,然后随心所欲地操作它:

let myGSlot = SKSpriteNode(color : .green, size: CGSize(width: 100.0, height: 100.0))

然而,当我尝试对其进行子类化时:

    class GuessSlot : SKSpriteNode{
        init(color: SKColor, size: CGSize) {
            super.init()
    }
   required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
}

无论我做什么,编辑都会给我很多错误。主要的是:

Must call a designated initializer of the superclass 'SKSpriteNode' Whether I put it in init() or super.init()

我知道我是 Swift 的新手,但这让我很难受!

********* 最新更新,也是我编译它但仍然崩溃并出现错误的唯一方法:

Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeec64aff0)

在调试器中,我可以看到参数的值为零

convenience init(color: SKColor, size: CGSize) {
        self.init(color: color, size: size)
        }

当我看到所有的帖子都对这个信息感到困惑时,我确实感觉不那么愚蠢了

在 Swift 中,您需要调用直接从您的超级 class 实现的初始化程序,在本例中为 SKSpriteNode。 super.init() 由SKSpriteNode 的继承树中的另一个class 实现,如SKNode 或NSObject。您始终可以检查 documentation 您可以为每个 class 调用哪些构造函数。了解您需要在 subclass

中调用指定的初始值设定项非常重要

例如,你可以这样做

class GuessSlot : SKSpriteNode{
   init(color: SKColor, size: CGSize) {
       super.init(texture: nil, color: color, size: size)
   }

   required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
   }
}

我不确定断开连接的位置,但正如评论中所述,您只需要覆盖正确指定的初始化纹理、颜色、大小。

class TestSpriteNode : SKSpriteNode{
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    override init(texture: SKTexture?, color: UIColor, size: CGSize) {
        super.init(texture: texture,color:color,size:size)
    }
}

这将使您能够访问 parent class.

的所有初始值

您现在可以var s = TestSpriteNode(color:.red,size:CGSize(width:1,height:1))

如果您需要覆盖此便利 init,则需要引用您覆盖的指定 init 之一,而不是便利 init。

class TestSpriteNode : SKSpriteNode{
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    override init(texture: SKTexture?, color: UIColor, size: CGSize) {
        super.init(texture: texture,color:color,size:size)
    }
    
    convenience init(color: UIColor, size: CGSize) {
        self.init(texture: nil,color:color,size:size)
    }
    
}