Search code examples
swiftuibuttonsprite-kittouchesbegan

Animate button when pressed and release


In many games and apps I have seen when you click on something, the button image change and while your finger is still on the botton and move it from the button, the image change again and the button is not clicked

In spriteKit I normaly do

  • gave the button a unique name
  • in touchesBegan I use nodeInPosition and then check the name of the node
  • if the names match some action is run

In ViewController

  • creat the button in the interface builder
  • creat outline and IBAction and inside of the method some action is run
  • if the button is made programmatically I use addTarget()

But I don't know how to animate the button when is pressed/hovered and release(return to default state) when the finger is not on button


Solution

  • You can set two images to the button for the highlighted and normal state like this

    button.setImage(imageUnhighlighted, forState: UIControlState.Normal)
    button.setImage(imageHighlighted, forState: UIControlState.Highlighted)