I have the following SKLabelNode
subclass:
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?()
}
}
}
I then instantiate the ButtonNode
using:
let button = ButtonNode("Label", action: { print("Action called") })
This doesn't work as I expect it to (the action is never called). Upon investigating I discovered that:
- In my intialiser the
buttonAction
property is notnil
- In the
touchesBegan
method, thebuttonAction
property isnil
Why does the buttonAction
property get set to nil
?