ON / OFF 按钮多次切换

ON / OFF Button toggles multiple times

我尝试为静音/取消静音按钮创建一个开/关按钮:

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 按钮,就像一个无限循环 !

有人有解决方案吗?

谢谢!

在您的 if 条件中使用 else 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")
}