Hassan A
Hassan A

Reputation: 337

Using a timer in Swift

First of all, I am very new to Swift programming, so please be patient with me! I am in the process of making PONG (classic game, I'm sure you've heard of it) for iOS in Swift. I am trying to make the game ball move around the screen. Now in VB (which is what I used to code in) I would just drag a timer to the view, set an interval and write something like ball.top - 5 in its own, personal sub. I don't really know how to go about this in Swift though, I have gotten as far as: NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "timerDidFire:", userInfo: nil, repeats: true) But I have no idea what this does, or where to write the code which is to be executed every time the timer fires. I also need to know how to enable and disable timers!!

Thanks a LOT for any help!

Upvotes: 0

Views: 1842

Answers (1)

user4226616
user4226616

Reputation:

First of all, you need to write a function named the same as your selector (by the way, I guess it's better to create a selector like this: Selector("timerDidFire:"), so your timer will look like timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("timerDidFire:"), userInfo: nil, repeats: true)). As I said before, now you need to write the function:

func timerDidFire(timer: NSTimer) {
   // something that will be executed each time the timer fires
}

Timer will be started immediately after this code: timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "timerDidFire:", userInfo: nil, repeats: true) will be executed. To disable the timer just write timer.invalidate() where you need. It's also better to make a timer for the whole class, to do that you need to write var timer = NSTimer() after the curly braces after the class definition (class ... : ... {). I believe that will help you, but nothing is better than reading swift docs.

Upvotes: 3

Related Questions