范围从类root到内部init,然后在touchesBegan里面?

时间:2016-11-09 22:23:21

标签: swift scope sprite-kit initialization

在这个内部,我没有看到goTo被分配到nextScene。我认为这是一个范围问题,但不知道解决它的问题:

//

import SpriteKit

class MenuButton: SKLabelNode {

    var goesTo: SKScene?

    override init() {
        super.init()
        print("test... did this get called? WTF? HOW/WHY/WHERE?")
    }

    convenience init(text: String, color: SKColor, destination: SKScene){
        self.init()
        self.text = text
        self.fontColor = color
        goesTo = destination
        self.isUserInteractionEnabled = true
        print("gooing tooooo....", text, goesTo!) // WORKS!!!
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        if let nextScene = goesTo {
        self.scene?.view?.presentScene(nextScene, transition: SKTransition.doorsOpenVertical(withDuration: 0.25))
        print("going to", nextScene) // This is NIL! SO NEVER GETS CALLED!
        }
    }

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

}

1 个答案:

答案 0 :(得分:1)

你的代码是正确的,你可以简单地测试它,例如a:

<强> GameScene.swift

self.imageview.image = [UIImage imageWithCIImage: [self generateBarcode:@"SOME STRING HERE"]];

你会在屏幕中间看到一个带有“HELLO”的红色标签。

正如您所看到的,您的打印效果也适用于您的两种方法。

<强> HelloScene.swift

import SpriteKit
class GameScene: SKScene {
    override func didMove(to view: SKView) {
        print("- \(type(of:self))")
        let helloScene = HelloScene.init()
        helloScene.name = "helloScene"
        let button1 = MenuButton.init(text: "HELLO", color: .red, destination: helloScene)
        addChild(button1)
        button1.position = CGPoint(x:self.frame.midX,y:self.frame.midY)
    }
}

调试控制台

enter image description here