我是Swift的新手 - 嘗試爲iPhone/iPad構建應用程序。希望您能夠幫助我。swift:停止倒數計時器爲零
我想包括一個從04:00分鐘到00:00倒計時的計時器。然後它應該停止在零並觸發音效(我還沒有嘗試過)。當您按下開始按鈕時,倒數開始(在我的代碼中,startTimer和stopTimer指向同一個按鈕;但是,按鈕僅在開始時被按下一次)。
計時器啓動並倒計時就好了。它按計劃將秒轉換成分鐘。但是,我的主要問題是我無法讓倒計時停止在零。它繼續超越00:0-1等。我該如何解決這個問題?
import Foundation
import UIKit
import AVFoundation
class Finale : UIViewController {
@IBOutlet weak var timerLabel: UILabel!
var timer = NSTimer()
var count = 240
var timerRunning = false
override func viewDidLoad() {
super.viewDidLoad()
}
func updateTime() {
count--
let seconds = count % 60
let minutes = (count/60) % 60
let hours = count/3600
let strHours = hours > 9 ? String(hours) : "0" + String(hours)
let strMinutes = minutes > 9 ? String(minutes) : "0" + String(minutes)
let strSeconds = seconds > 9 ? String(seconds) : "0" + String(seconds)
if hours > 0 {
timerLabel.text = "\(strHours):\(strMinutes):\(strSeconds)"
}
else {
timerLabel.text = "\(strMinutes):\(strSeconds)"
}
}
@IBAction func startTimer(sender: AnyObject) {
var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
}
func stopTimer() {
if count == 0 {
timer.invalidate()
timerRunning = false
}
}
@IBAction func stopTimer(sender: AnyObject) {
timerRunning = false
if count == 0 {
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("stopTimer"), userInfo: nil, repeats: true)
timerRunning = true
}}
}
http://stackoverflow.com/a/29583418/2303865 –