swift - 从类根到 init 内部,再到 touchesBegan 内部的作用域?

标签 swift scope sprite-kit initialization

在这里面,我没有看到 goesTo 被分配给 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")
    }

}

最佳答案

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

GameScene.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)
    }
}

您会在屏幕中间看到一个红色标签,上面写着“HELLO”。

如您所见,您的打印品对于您的两种方法来说看起来都不错。

HelloScene.swift

import Foundation
import SpriteKit
class HelloScene: SKScene {
     override func didMove(to view: SKView) {
        print("- \(type(of:self))")
        self.backgroundColor = .blue
     }
}

调试控制台:

enter image description here

关于swift - 从类根到 init 内部,再到 touchesBegan 内部的作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40517013/

相关文章:

swift - 有没有办法在 SwiftUI 中为 TextField 设置 inputView?

Javascript OOP 原型(prototype)函数返回未定义

java - 解决组件问题 - 范围

ios - arc4random 和 arm64 与 swift

objective-c - 检测 Sprite 套件中数组中的对象之间的碰撞

ios - 在游戏场景中隐藏 iAd 横幅?

ios - 如何使用 ios-charts 在饼图 View 中获取所选切片的索引?

xcode - 我的代码有什么问题(云套件)

ios - UICollectionView重用单元格背景问题

javascript - 术语 "global property"和 "global variable"是同义词吗?