我有以下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
?