ios - Countdown with several decimal slots, using NSTimer in Swift -
i want make app has timer starting @ 10.0000000 example, , want countdown here's code far:
import uikit class viewcontroller: uiviewcontroller { @iboutlet weak var labeltime: uilabel! var counter = 10.0000000 var labelvalue: double { { return nsnumberformatter().numberfromstring(labeltime.text!)!.doublevalue } set { labeltime.text = "\(newvalue)" } } override func viewdidload() { super.viewdidload() // additional setup after loading view, typically nib. labelvalue = counter var timer = nstimer.scheduledtimerwithtimeinterval(0.0000001, target: self, selector: ("update"), userinfo: nil, repeats: true) } func update(){ labelvalue -= 0.0000001 } }
what happens countdown slow, it's not working , take 1 hour 0 seconds, instead of 10 seconds. ideas? changes should make code? thanks
timers not super-accurate, , resolution of nstimer 1/50th of second.
plus, refresh rate of iphone screen 60 frames/second, it's totally pointless run timer faster that.
rather trying use timer decrement every time fires, create timer fires 50 times second, , have use clock math update display based on remaining time:
var futuretime: nstimeinterval override func viewdidload() { super.viewdidload() labelvalue = counter //futuretime value 10 seconds in future. futuretime = nsdate.timeintervalsincereferencedate() + 10.0 var timer = nstimer.scheduledtimerwithtimeinterval( 0.02, target: self, selector: ("update:"), userinfo: nil, repeats: true) } func update(timer: nstimer) { let timeremaining = futuretime - nsdate.timeintervalsincereferencedate() if timeremaining > 0.0 { label.text = string(format: "%.07f", timeremaining) } else { timer.invalidate() //force label 0.0000000 @ end label.text = string(format: "%.07f", 0.0) } }
Comments
Post a Comment