使用SKLabelNode的子类时遇到麻烦

时间:2017-01-31 13:39:25

标签: swift sklabelnode

我已经写了一个SKLabelNode的自定义子类,它应该在我的标签上应用一个基本的“阴影”:

class ShadowLabel: SKLabelNode {
    var shadowNode: SKLabelNode

    init(fontNamed font: String = "Foo", text: String, size: CGFloat, zPosition zPos: CGFloat, shadowColor: SKColor = SKColor.black, shadowOffset: CGPoint = CGPoint(x: 0, y: -4), shadowAlpha: CGFloat = 0.5) {
        shadowNode = SKLabelNode(fontNamed: font)

        super.init(fontNamed: font)
        self.text = text
        self.fontSize = size
        self.zPosition = zPos

        shadowNode.text = self.text
        shadowNode.zPosition = self.zPosition - 1
        shadowNode.fontColor = shadowColor
        shadowNode.position = shadowOffset
        shadowNode.fontSize = self.fontSize
        shadowNode.alpha = 0.5

        self.addChild(shadowNode)
    }

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

    func setNewText(_ newText: String) {
        self.text = newText
        self.shadowNode.text = newText
    }
}

我的问题是,在运行时,控制台给出了以下错误:

  

对类使用未实现的初始化程序'init()'   'MyProject.ShadowLabel'

我在我的GameScene类中使用自定义子类如下:

class GameScene: SKScene {
    var scoreLabel = (ShadowLabel(fontNamed: "Foo", text: "", size: 100, zPosition: 150, shadowColor: SKColor.black, shadowOffset: CGPoint(x: 0, y: -4), shadowAlpha: 0.5))

    override func didMove(to view: SKView) {
        scoreLabel.text = "\(gameScore.totalScore)" // a struct which counts the game score
        scoreLabel.color = SKColor.white
        scoreLabel.fontSize = 100
        scoreLabel.zPosition = 150
        scoreLabel.position = CGPoint(x: Scene.width/2, y: Scene.heigth - 40 - scoreLabel.frame.height)
        addChild(scoreLabel)
    }
}

我不知道为什么首先调用参数为空的init()。

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

您仍然需要使用无参数初始化方法。

override init() {
    shadowNode = SKLabelNode()
    super.init()
}

你必须将你的shadowNode设置为相等的东西,这可能会破坏你正在进行的其他事情。

我倾向于将节点存储在节点的子数组中,所以我不必处理这样的事情,不确定它是否是最好的做法。

答案 1 :(得分:0)

我找到了一个非优雅的解决方法来解决我的问题(需要额外的overlayNode,因为通过将shadowNode视为主标签节点的子节点,无论您选择什么zPosition,它都会覆盖主节点,所以overlayNode “恢复”阴影效果):

let coinEnd = UIImage(/*HERE_LEFT_BLANK_IMG*/).resizableImage(withCapInsets:
        UIEdgeInsetsMake(0,7,0,7), resizingMode: .stretch)
.
.
.
.

override func trackRect(forBounds bounds: CGRect) -> CGRect {
    var result = super.trackRect(forBounds: bounds)
    result.origin.x = 0
    result.size.width = bounds.size.width
    result.size.height = 10 //added height for desired effect
    return result
}

override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect {
    return super.thumbRect(forBounds:
        bounds, trackRect: rect, value: value)
        .offsetBy(dx: 0/*Set_0_value_to_center_thumb*/, dy: 0)
}