我有多個視圖,每個與自己的計時器相關聯。但是,每次只有一個視圖正在運行一段時間。我正在訪問for ... in循環中的每個視圖,如果前一個視圖中的前一個定時器已停止,而我在選擇器方法中使其失效,則我想爲下一個視圖啓動時間。如何使一個計時器在swift中循環工作?
的代碼如下所示:
var timer = NSTimer()
let timeInterval:NSTimeInterval = 1
var views = [TimerView]()
var timeCountDown: NSTimeInterval = 0
override func viewDidLoad() {
//viewDidLoad create the necessary UIView and fill the views array then pass them to a call to startTimer:
startTimer(views)
}
//startTimer function create the countdown timer
func startTimer(timerViews: [TimerView]){
for timerView in timerViews {
if !timer.valid { // a view with its associated timer start only when the previous timer has run its course and is invalidated
//creating a timer to associate with the current view
timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval,
target: self,
selector: "timerDidEnd:",
userInfo: timerView,
repeats: true)
}
}
}
//Callback function
func timerDidEnd(timer: NSTimer){
let timerView = timer.userInfo as! TimerView
timeCountDown = timeCountDown - timeInterval
timerView.timeLabel.text = timeToString(timeCountDown)
timerView.curValue = CGFloat(timeCountDown)
if timeCount <= 0.0 {
resetTimeCount()
}
}
func timeToString(time:NSTimeInterval) -> String {
let minutes = Int(time)/60
let seconds = time - Double(minutes) * 60
return String(format:"%02i:%02i",minutes,Int(seconds))
}
func resetTimeCount(){
timer.invalidate()
}
隨着三視圖我得到這個輸出一些打印調試:「運行for循環」,「通過循環調用視圖#1」,「調用定時器「,」通過for循環調用視圖#2「,」通過for循環調用視圖#3「,」倒計時開始「...這就是倒數只在for循環終止後開始。
我遇到的問題是第一個定時器在for循環調用我的視圖數組中的所有視圖時運行。在迭代到下一個視圖之前,我如何讓for循環等待定時器失效?
我想要實現的是:第一個視圖開始倒計時;當倒計時結束時出現並且進行倒計時。然後第三個視圖與新的倒計時等等,直到最後一個視圖。但它看起來像與集合中的第一視圖相關聯的第一計時器前環在我的代碼完成循環真正開始
感謝
編輯:我想知道,如果計時器沒有在不同的線程運行比for循環?
更準確地解釋你想要完成的事情。每個計時器視圖應該啓動多少次?你想永遠圍繞觀點去觀看,還是每次觀看定時器只觀看一次? – matt
你好馬特!數組中的視圖數量有限。每個視圖應該啓動自己的定時器,當前一個視圖中的前一個定時器停止時,該定時器將開始出現。 – irkinosor
視圖#1的計時器從倒數0到10秒作爲倒計時運行,然後失效。應該啓動視圖#2,同一個定時器再次從0s運行到10s,直到最後一個視圖#n。我認爲for循環只會在計時器失效時迭代,但似乎並非如此 – irkinosor