我试图为静音/取消静音声音按钮创建一个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按钮,就像无限循环一样!
有人有解决方案吗?
谢谢 !
I trie to create an ON / OFF button for the mute / unmute sound button :
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") } } }But nothing happened, because when I touch the button, it is removed and the OFF button is added, but the application detect that I touch the OFF button, so it remove it and add the ON button, like an infinite loop !
Someone has a solution ?
Thank you !
最满意答案
else if在你的if条件下使用else if 。 否则两个条件都将被执行。 这就是您的代码失败的原因。 执行第一个条件时,放置soundOffButton而不是soundOnButton 。 当执行到达第二个条件时,该点上的节点是soundOffButton ,因此按钮也会互换。 else if确保一次只执行一个条件,则使用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") }use else if in your if conditions. Otherwise both conditions will be executed. This is why your code fails. When the first condition is executed you place the soundOffButton instead of soundOnButton. When the executing reaches the second condition, the node at the point is soundOffButton, so again the buttons are interchanged. Using else ifensure that only one condition is executed at a time.
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") }更多推荐
发布评论