1
votes

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.

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) {

        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
post some code and please point where exactly you are having problem. What works and what doesn't. This will help you get an answer quickly. - Vig
Does the view has any "touchable" object?, I mean, what If you add a gesture recognizer to the whole view, that works for you?, If so I can write down how you can do it. - Fantini
I'm fairly new to iOS development and I couldn't even understand where to start. I do have a touches began method, which applies an impulse to the object and thats it, but I can't understand how to go about it. - Sharukh
To clarify, after the user touches anywhere on the screen, you want to app to start randomly placing new objects (random times, random position)? - nielsbot
Yes, for which I have the spawnObject method. - Sharukh

2 Answers

2
votes

In your viewDidLoad() method add the following code:

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.

0
votes

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() 

}
    }
}