How do I programmatically add a button that will run an action when it\'s clicked? What code would be used?
I am used to just adding a button in the storyboard and r
Mike S - Answer updated for - Swift 5.2
override func didMove(to view: SKView) {
createButton()
}
func createButton()
{
// Create a simple red rectangle that's 100x44
button = SKSpriteNode(color: SKColor.red, size: CGSize(width: 100, height: 44))
// Put it in the center of the scene
button.position = CGPoint(x:self.frame.midX, y:self.frame.midY);
self.addChild(button)
}
override func touchesEnded(_ touches: Set, with event: UIEvent?) {
let touch = touches.first
let touchLocation = touch!.location(in: self)
// Check if the location of the touch is within the button's bounds
if button.contains(touchLocation) {
print("tapped!")
}
}