james
james

Reputation: 2663

Subclassing SKLabelNode error with Swift

I have the following class that is a subclass of SKLabelNode. This class will not work without the

override init(){
        super.init()
    }

call. It seems that SKLabelNode is trying to call an init() method with no parameters, or something else is going on somewhere that is causing this issue.

Here is the simplified class.

import UIKit
import SpriteKit

class PulsatingText: SKLabelNode {

    override init(){
        super.init()
    }

    init (fontNamed:String!, theText: String!, theFontSize: CGFloat!){
        super.init(fontNamed: fontNamed)
        self.text = theText
        self.fontSize = theFontSize
    }


    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

If i remove the

override init(){
            super.init()
        }

I get a runtime crash with the following error logged to the console.

fatal error: use of unimplemented initializer 'init()' for class 'MobileTutsInvaderz.PulsatingText'

Here is how I am calling the method.

let invaderText = PulsatingText(fontNamed: "ChalkDuster", theText: "INVADERZ", theFontSize:50)

I am also including a image of the stack trace below.

,

Upvotes: 1

Views: 919

Answers (2)

Nikita Ivaniushchenko
Nikita Ivaniushchenko

Reputation: 1435

Since you only want to add convenience initializer and leave the rest as is, you don't need to override designated initializers. So just change your code like this:

class PulsatingText: SKLabelNode {

    convenience init (fontNamed:String!, theText: String!, theFontSize: CGFloat!){
        self.init(fontNamed: fontNamed)
        self.text = theText
        self.fontSize = theFontSize
    }
}

Upvotes: -1

Christian
Christian

Reputation: 22343

You need to initialize the init() method. Because the default init() method gets called everytime you initialize a SKLabelNode. You can test it by implementing the override init() and add an println statement like that:

override init() {
    super.init()
    println("test")
}

If you now init a labelnode like that:

var label:PulsatingText = PulsatingText(fontNamed: "Arial", theText: "hey", theFontSize: 12)

The println("test") will get called.

Upvotes: 2

Related Questions