即使调用Swift SpriteKit中的removeFromParent(),按钮仍然有效

时间:2018-01-30 21:00:05

标签: swift sprite-kit

在下面的代码中,如果我按下removeButton按钮会消失,但它仍然有效。也许我应该将if语句设为false,但我不知道如何。

class GameScene : SKScene {

    var button : SKSpriteNode!
    var removeButton : SKSpriteNode!
    var image : SKSpriteNode!

    override func didMove(to view: SKView) { 
        createButton()
        createRemoveButton()
    }

    func createButton() {
        button = SKSpriteNode(imageNamed: "button")
        button.position = CGPoint(x: -300,y: 0)
        self.addChild(button)
    }

    func createRemoveButton() {
        removeButton = SKSpriteNode(imageNamed: "removeButton")
        removeButton.position = CGPoint(x: 300,y: 0)
        self.addChild(removeButton)
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        let touchLocation = touch!.location(in: self)
        if button.contains(touchLocation) {
            image = SKSpriteNode(imageNamed: "image")
            image.position = CGPoint(x: 0,y: 300)
            self.addChild(image)
        }
        if removeButton.contains(touchLocation) {
            button.removeFromParent()
        }
    }
    override func update(_ currentTime: TimeInterval) {
    }
}

2 个答案:

答案 0 :(得分:1)

您需要了解ARC(自动引用计数)以及保留实例所需的内容。

在您的情况下,您是保留按钮,这意味着它不会从内存中删除。

现在当您从父级移除按钮时,按钮的框架仍然完全相同,唯一不同的是button.parent现在是nil

当你致电button.contains(touchLocation)时,这将会过去,因为你不关心按钮是否在现场,你所做的只是检查touchLocation是否在{{1}内1}}按钮。

最快的解决方法是检查父级:

frame

实际上,您需要学习如何更好地管理资源。我建议您尝试查找有关ARC如何工作的教程。

答案 1 :(得分:0)

这是正常的,因为你不使用好的按钮。您使用button代替removeButton

你应该这样做:

if removeButton.contains(touchLocation) {
   removeButton.removeFromParent()
}

现在它应该正常工作

相关问题