首页 文章

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

提问于
浏览
1

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

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

func viewdidload() {

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

}

func viewTapped(recognizer: UITapGestureRecognizer) {

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

}

我想我错过了一些东西 .

这是我的触摸开始方法:覆盖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

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

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

    然后实现以下方法:

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

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

  • 2

    如果你想只调用一次函数...然后声明一个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() 
    
    }
        }
    }
    

相关问题