在Swift中对SpriteKit类进行子类化

时间:2014-06-06 14:59:09

标签: ios swift

我对iOS开发非常陌生,但我一直在玩SpriteKit模板应用程序,以了解工作原理,并尝试在Swift上启动。我遇到麻烦的一件事是如何使用SpriteKit子类。

我在GameScene.swift文件中,我试图为" Hello World"提取课程。标签,所以这里的文件是什么样的:

//  GameScene.swift

import SpriteKit

class HelloLabel: SKLabelNode {
    init(fontNamed: String) {
        super.init(fontNamed: fontNamed)
        self.text = "Hello, World!"
        self.fontSize = 65;
        self.position = CGPoint(x: 400, y: 500);
    }
}

class GameScene: SKScene {
    override func didMoveToView(view: SKView) {
        /* Setup your scene here */
//        let myLabel = SKLabelNode(fontNamed:"Chalkduster")
//        myLabel.text = "Hello, World!";
//        myLabel.fontSize = 65;
//        myLabel.position = CGPoint(x: 400, y: 500);

        let myLabel = HelloLabel(fontNamed: "Chalkduster")
        self.addChild(myLabel)
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        /* snip, no changes made here */
    }

    override func update(currentTime: CFTimeInterval) {
        /* snip, no changes made here */
    }
}

因此,HelloLabel旨在成为一个传递,试图了解所有内容是如何连接在一起的,但是当我运行应用程序时,我收到以下错误:

/Users/jon/Projects/ErrorExample/ErrorExample/GameScene.swift: 11: 11: fatal error: use of unimplemented initializer 'init()' for class 'ErrorExample.HelloLabel'

我不明白这条消息试图告诉我的是什么。我读这个错误的方式是它抱怨我没有在类init中实现一个名为ErrorExample.HelloLabel的初始化程序,但它确实看起来像我一样!

那么,我在这里做错了什么 - 如何提取一个类来隐藏所有这些设置?

4 个答案:

答案 0 :(得分:11)

我不确定为什么,但SKLabelNode中隐藏的功能试图调用没有参数的init函数。这似乎有效:

class HelloLabel: SKLabelNode {
    init() {
        super.init()
    }

    init(fontNamed fontName: String!) {
        super.init(fontNamed: fontName)
        self.text = "Hello, World!"
        self.fontSize = 65;
        self.position = CGPoint(x: 400, y: 500);
    }
}

答案 1 :(得分:2)

这似乎更好:

class LinkLabel: SKLabelNode {

    override init() {
        super.init()
    }

    override init(fontNamed fontName: String!) {
        super.init(fontNamed: fontName)
        self.text = "Hello, World!"
        self.fontSize = 65;
        self.position = CGPoint(x: 400, y: 500);
    }

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

}

答案 2 :(得分:0)

也许是因为超类期望NSString*更改init(fontNamed: String) {init(fontNamed: NSString) {会解决问题?

或者另一种可能性是使用obj-c桥接:

init(fontNamed: String) {
    super.init(fontNamed: fontNamed.bridgeToObjectiveC())
    ...
}

答案 3 :(得分:-1)

您必须先进行类初始化,然后再初始化超类。所以你的init()应该是这样的:

init(fontNamed: String) {
        self.text = "Hello, World!"
        self.fontSize = 65;
        self.position = CGPoint(x: 400, y: 500);
        super.init(fontNamed: fontNamed)
    }

这是由于安全性,并在WWDC会议403中解释,中级Swift

相关问题