2016-08-01 77 views
1

你好我正在開發一個倒數計時器,它必須在8小時後停止。那就是:如何使用Swift做CountDown計時器

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

但有28800秒(這是8小時)我想顯示08:00:00,07:59:59,七點59分58秒,等等...代替目前它正在顯示28800,2899,28798等。你有一個想法如何格式化爲一個真正的時鐘(08:00:00)?

回答

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警告有關使用 「讓」 或「VA的R」爲小時/分/秒,但它仍然有效)

結果是這樣的:

00:00:00