[英]How do I stop a function from being called until there is a touch on the screen?
I have an object on screen as soon as the app launches. 应用启动后,屏幕上就会出现一个对象。 I have a method that randomly starts placing more of that same object when the app launches, but I want that to happen after the app registers a touch. 我有一种方法,可以在应用启动时随机开始放置更多相同对象,但是我希望这种情况在应用注册触摸后发生。 How can I do that? 我怎样才能做到这一点? I think it would have to be something in my touches began method, but I can't seem to get my code working. 我认为这一定是我接触的begin方法,但是我似乎无法使我的代码正常工作。
This is what I did after Jacob's post: 这是我在雅各布的帖子之后所做的:
func viewdidload() {
self.view!.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "viewTapped:"))
}
func viewTapped(recognizer: UITapGestureRecognizer) {
func spawnObject()
self.view!.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "viewTapped:"))
}
I think I'm missing something out of this. 我想我从中错过了一些东西。
Here is my touches began method: override func touchesBegan(touches: Set, withEvent event: UIEvent) { 这是我接触的开始方法:覆盖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()
}
}
In your viewDidLoad() method add the following code: 在您的viewDidLoad()方法中,添加以下代码:
self.view.addGestureRecognizer(UITapGestureRecognizer(self, "viewTapped:"))
Then implement the following method: 然后实现以下方法:
func viewTapped(recognizer: UITapGestureRecognizer) {
CALL YOUR METHOD HERE
self.view.removeGestureRecognizer(UITapGestureRecognizer(self, "viewTapped:"))
}
This now means that as soon as a tap is registered anywhere on the screen, your method will be called. 现在这意味着,只要在屏幕上的任意位置注册了点击,便会调用您的方法。
if you want the function to be called only for once...then declare a 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()
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.