我對Xcode(swift)很陌生,簡而言之,我試圖製作一個倒數計時器,倒計時秒數和小數點。用毫秒創建倒數計時器(NSTimer),但它不能正確倒計數
它倒計時,因爲它應該,但是,例如,當我從13秒倒數,它真的需要23秒,當我手動計時。 這可能是一個簡單的解決方案,但我已經嘗試了很多東西,無法弄清楚如何解決它。
這裏是我的代碼:
import UIKit
var timer = NSTimer()
var seconds = 13
var milliseconds = 0
class ViewController: UIViewController {
@IBOutlet weak var Label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Label.text = "\(seconds).\(milliseconds)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func Button(sender: AnyObject) {
timer = NSTimer.scheduledTimerWithTimeInterval(0.001, target: self, selector: Selector("countDownfunction"), userInfo: nil, repeats: true)
}
func countDownfunction() {
Label.text = "\(seconds).\(milliseconds)"
if milliseconds == 0 {
seconds -= 1
milliseconds = 100
} else {
milliseconds -= 1
}
}
}
編輯:新的代碼還沒有計算出來,但是,正確的方式我想,我怎樣才能。減去/像我一樣在比較兩個字符串:標籤。 text =(countdownSeconds - elapsedTime) 它給了我一個錯誤,我不能' - '兩個字符串,我不知道如何比較兩秒鐘。謝謝
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var Label: UILabel!
var startTime = NSDate.timeIntervalSinceReferenceDate()
var currentTime = NSDate.timeIntervalSinceReferenceDate()
var elapsedTime = String()
var differenceTime = String()
var countdownSeconds = String()
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 Button(sender: AnyObject) {
countdownSeconds = String(10)
startTime = NSDate.timeIntervalSinceReferenceDate()
NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("countDownUpdateMethod"), userInfo: nil, repeats: true)
}
func countDownUpdateMethod(){
currentTime = NSDate.timeIntervalSinceReferenceDate()
elapsedTime = String(currentTime - startTime)
Label.text = (countdownSeconds - elapsedTime)
}
}
'NSTimer'分辨率不夠高 – dan