Gabe12 Gabe12 - 7 months ago 289
Swift Question

Using TouchesMoved in Swift 2

I'm making a SpriteKit game in XCode using swift. I want to make custom buttons in the menu, and I'm following this tutorial to do it. Everything's working fine except the touchesMoved function.

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
var touch: UITouch = touches.allObjects[0] as UITouch
var location: CGPoint = touch.locationInNode(self)

if defaultButton.containsPoint(location) {
activeButton.hidden = false
defaultButton.hidden = true
} else {
activeButton.hidden = true
defaultButton.hidden = false
}
}


Apparently, the "touches.allObjects[0] as UITouch" doesn't work anymore in Swift 2. I've searched for alternatives, but I haven't found any that works. How could I replace that line of code?

Answer

The correct way to do it is this:

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

        for touch: AnyObject in touches {

            let location = touch.locationInNode(self)

            if defaultButton.containsPoint(location) {
                activeButton.hidden = false
                defaultButton.hidden = true
            } else {
                activeButton.hidden = true
                defaultButton.hidden = false
            }
        }
    }