为什么我对SKLabelNode子类的关闭属性变为零?

时间:2019-07-26 22:54:29

标签: swift properties closures sklabelnode

我有以下SKLabelNode子类:

class ButtonNode: SKLabelNode {
    // The only reason this is optional is because of the required init() method.
    private var buttonAction: (() -> Void)?

    init(_ text: String, action: @escaping () -> Void) {
        self.buttonAction = action

        // Initialise the button label node.
        super.init(fontNamed: "Futura")
        self.isUserInteractionEnabled = true
        self.text = text
        self.fontColor = SKColor.white
    }

    override init() {
        super.init()
    }

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

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if touches.first?.location(in: self) != nil {
            self.buttonAction?()
        }
    }
}

然后我使用以下方法实例化ButtonNode

let button = ButtonNode("Label", action: { print("Action called") })

这不符合我的预期(永远不会调用该动作)。经过调查,我发现:

  • 在我的初始化器中,buttonAction属性不是 nil
  • touchesBegan方法中,buttonAction属性为nil

为什么将buttonAction属性设置为nil

0 个答案:

没有答案