如何在屏幕触摸之前停止调用函数?

时间:2015-07-17 14:40:41

标签: ios iphone xcode swift

一旦应用程序启动,我就会在屏幕上显示一个对象。我有一个方法,在应用程序启动时随机开始放置更多相同的对象,但我希望在应用程序注册触摸后发生这种情况。 我怎样才能做到这一点?我认为它必须是我触摸开始的方法,但我似乎无法让我的代码工作。

这是我在雅各布的帖子之后所做的:

func viewdidload() {

    self.view!.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "viewTapped:"))

}

func viewTapped(recognizer: UITapGestureRecognizer) {

   func spawnObject() 
   self.view!.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "viewTapped:")) 

}

我想我错过了一些东西。

这是我的触摸开始方法:      override func touchesBegan(touches:Set,withEvent event:UIEvent){

        if let touch = touches.first as? UITouch {

        if self.touch == false {

            self.touch = true
            self.spawnObjects()

        }

        }

        if !ball.physicsBody!.dynamic {

        startGameTextNode.removeFromParent()
        ball.physicsBody!.dynamic = true
    }

    if (moving.speed > 0) {
        ball.physicsBody!.velocity = CGVectorMake(0, 0)
        ball.physicsBody!.applyImpulse(CGVectorMake(0, 8))
    } else if (canRestart) {
        self.resetScene()
    }
}

2 个答案:

答案 0 :(得分:2)

在viewDidLoad()方法中添加以下代码:

self.view.addGestureRecognizer(UITapGestureRecognizer(self, "viewTapped:"))

然后实现以下方法:

func viewTapped(recognizer: UITapGestureRecognizer) {

CALL YOUR METHOD HERE
self.view.removeGestureRecognizer(UITapGestureRecognizer(self, "viewTapped:"))
}

现在这意味着只要在屏幕上的任何位置注册了点按,您的方法就会被调用。

答案 1 :(得分:0)

如果你想只调用一次函数...然后声明一个bool

var touched = false

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        if let touch = touches.first as? UITouch {
          if self.touched == false {
          self.touched = true
          spawnObject() 

}
    }
}