1

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 not nil
  • In the touchesBegan method, the buttonAction property is nil

Why does the buttonAction property get set to nil?

DanielGibbs
  • 9,910
  • 11
  • 76
  • 121

0 Answers0