如何使用Swift执行CountDown计时器

时间:2016-08-01 13:19:22

标签: format nstimer countdown

您好我正在开发倒数计时器,必须在8小时后停止。这是:

import UIKit

class ViewController: UIViewController {

   var timer = NSTimer()
   var counter = 0

@IBOutlet weak var Label: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
  // Do any additional setup after loading the view, typically from a   nib.
}

 override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
  // Dispose of any resources that can be recreated.
 }

@IBAction func Start(sender: AnyObject) {
counter = 28800
Label.text = String(counter)
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTimer"), userInfo: nil, repeats: true)
     }

  func updateTimer () {

counter -= 1
Label.text = String(counter)

 }

 @IBAction func Stop(sender: AnyObject) {

timer.invalidate()
 }
 }

但是我要显示08:00:00,07:59:59,07:59:58,而不是28800秒(也就是8小时),等等...此时显示28800秒, 28799,28798,等等。您是否知道如何将其格式化为真正的时钟(08:00:00)?

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,而且在xcode / swift中几乎是一个菜鸟 - 但在回顾了几个来源之后,这就是我放在一起对我有用的东西:

替换您的

func updateTimer () {

counter -= 1
Label.text = String(counter)
}

有了这个:

func updateTimer () {
        counter -= 1
        let hours = Int(counter) / 3600
        let minutes = Int(counter) / 60 % 60
        let seconds = Int(counter) % 60
        Label.text = String(format: "%02i:%02i:%02i",hours,minutes,seconds)
}

(xcode 8.1警告使用“let”或“var”几小时/分钟/秒,但它仍然有效)

结果如下:

00:00:00