ON / OFF按钮多次切换

时间:2015-02-18 22:15:33

标签: swift button sprite-kit

我试图为静音/取消静音声音按钮创建一个ON / OFF按钮:

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
        for touch: AnyObject in touches {

            let location = touch.locationInNode(self)

            let resizeAction = SKAction.scaleTo(1, duration: 0.05)

            let fadeAnimation = SKTransition.fadeWithColor(SKColor.whiteColor(), duration: 0.4)            

            if self.nodeAtPoint(location) == soundOnButton {

                soundOnButton.removeFromParent()
                self.addChild(soundOffButton)
                println("test 1")

            }


            if self.nodeAtPoint(location) == soundOffButton {


                soundOffButton.removeFromParent()
                self.addChild(soundOnButton)
                println("test 2")


            }

        }

 }

但是什么也没发生,因为当我触摸按钮时,它被移除并且添加了OFF按钮,但应用程序检测到我触摸了OFF按钮,因此将其移除并添加ON按钮,就像无限循环一样!

有人有解决方案吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

else if条件中使用if。否则两个条件都将被执行。这就是您的代码失败的原因。执行第一个条件时,请放置soundOffButton而不是soundOnButton。当执行到达第二个条件时,该点上的节点为soundOffButton,因此按钮也会互换。使用else if确保一次只执行一个条件。

if self.nodeAtPoint(location) === soundOnButton {

    soundOnButton.removeFromParent()
    self.addChild(soundOffButton)
    println("test 1")

}
else if self.nodeAtPoint(location) === soundOffButton { // Changed line
    soundOffButton.removeFromParent()
    self.addChild(soundOnButton)
    println("test 2")
}