[英]Swift countDown timer Logic
我正在按天,小時和秒創建一個倒數計時器。 我目前將它們存儲在String數組中,同時還將它們轉換為Int(使用map()
),以便在將值制成標簽時可以倒數/遞減。
打印到日志時的當前輸出為: ["[68168]", "[68188]", "[68243]", "[68281]"]
我在形成countDown函數的邏輯時遇到了麻煩,因此當秒數達到“ 0”時,1分鍾下降,而59分鍾后,1小時遞減,依此類推,直到達到“ 00:00:00”。
在每個索引中,我具有[小時,分鍾,秒]的3個值。 但是我有幾個索引。
目前,我正在使用小時* 3600,分鍾* 60 +秒。 我的問題是如何在countDown函數中將其分解並分解...
這是我的代碼:
//Here I'm querying and converting the objects into Hour, Minute, Seconds.
var createdAt = object.createdAt
if createdAt != nil {
let calendar = NSCalendar.currentCalendar()
let comps = calendar.components([.Hour, .Minute, .Second], fromDate: createdAt as NSDate!)
let hour = comps.hour * 3600
let minute = comps.minute * 60
let seconds = comps.second
let intArray = [hour, minute, seconds]
//Now i'm appending to the String array below.
self.timeCreatedString.append("\(intArray)")
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("countDown"), userInfo: nil, repeats: true)
}
func countDown() {
//completely stuck as to how to decrement/divide up the values so that I can display it as: 23:49:01 (Hours, minutes, seconds).
}
如何形成表格,以便每個索引中的每個元素分別倒數? 例如:“ 23:59:59”
PS,這是建立在TableViewController上的。 我想將此打印到cellForRowAtIndexPath
方法的單元格視圖控制器中的標簽
在一個稱為countdown
變量中,以秒為單位保持倒數時間:
var countdown = 7202 // two hours and two seconds
需要顯示時,將其分成hours
, minutes
和seconds
然后使用String(format:)
構造函數對其進行格式化:
// loop 5 times to demo output
for _ in 1...5 {
let hours = countdown / 3600
let minsec = countdown % 3600
let minutes = minsec / 60
let seconds = minsec % 60
print(String(format: "%02d:%02d:%02d", hours, minutes, seconds))
countdown--
}
輸出:
02:00:02 02:00:01 02:00:00 01:59:59 01:59:58
如果您有多個計時器,請將它們放在一個數組中:
// Array holding 5 different countdown timers referred to as
// timers[0], timers[1], timers[2], timers[3] and timers[4]
var timers = [59, 61, 1000, 3661, 12345]
for i in 0 ..< times.count {
let hours = timers[i] / 3600
let minsec = timers[i] % 3600
let minutes = minsec / 60
let seconds = minsec % 60
print(String(format: "%02d:%02d:%02d", hours, minutes, seconds))
}
輸出:
00:00:59 00:01:01 00:16:40 01:01:01 03:25:45
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.