在Swift中对SpriteKit类进行子类化 [英] Subclassing SpriteKit classes in Swift

查看:191
本文介绍了在Swift中对SpriteKit类进行子类化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm very new to iOS development, but I've been playing around with the SpriteKit template app to learn how things work and try to boot up on Swift while I'm at it. One thing I'm having trouble with is how to work with SpriteKit subclasses.

我在GameScene.swift文件中,我正在尝试提取一个类Hello World标签,所以这里是该文件的样子:

I'm in the GameScene.swift file and I'm trying to extract a class for the "Hello World" label, so here's what that file looks like:

//  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 旨在成为一个传递,试图了解所有内容连接在一起,但是当我运行应用程序时,我收到以下错误:

So, HelloLabel is intended to just be a pass-through in an attempt to understand how everything wires together, but when I run the app, I get the following error:

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

我不明白这条消息试图告诉我的是什么。我读这个错误的方式是它抱怨我没有在类 ErrorExample.HelloLabel init 的初始化程序c>,但看起来我确实对我这么做了!

I'm not understanding what this message is trying to tell me. The way I read this error is that its complaining that I haven't implemented an initializer called init in the class ErrorExample.HelloLabel, but it sure looks like I have to me!

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

So, what am I doing wrong here - how does one extract a class to hide all this setup?

推荐答案

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

I'm not certain exactly why, but the hidden functionality inside SKLabelNode was trying to call an init function with no parameters. This seems to work:

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);
    }
}

这篇关于在Swift中对SpriteKit类进行子类化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆