swift - How do I add a timer to an iOS app that ends the game when the timer reaches 0? -
i making quiz app using swift. want add timer countsdown 60 seconds (1 minute) when reaches 0, game over. how add timer?
this you, put appropriate game logic on updatetimer function , stopcountdowntimer function.
class timertestviewcontroller: uiviewcontroller { var totalsecondscountdown = 60 // 60 seconds // timer var timer : nstimer! override func viewdidload() { super.viewdidload() self.startcountdowntimer() } func updatetimer() { if self.totalsecondscountdown > 0 { self.totalsecondscountdown = self.totalsecondscountdown - 1 println("timer countdown : \(self.totalsecondscountdown)") } else { self.stopcountdowntimer(); println("timer stops ...") } } func startcountdowntimer() { if self.timer != nil { self.timer.invalidate() self.timer = nil } if self.totalsecondscountdown > 0 { self.timer = nstimer.scheduledtimerwithtimeinterval(1.0, target: self, selector: "updatetimer:", userinfo: nil, repeats: true) nsrunloop.currentrunloop().addtimer(self.timer, formode: nsrunloopcommonmodes) self.timer.fire() } } func stopcountdowntimer() { if self.timer != nil { self.timer.invalidate() self.timer = nil } } }
Comments
Post a Comment