Swift countDown计时器逻辑

时间:2015-10-28 14:32:32

标签: arrays swift nsdate countdown decrement

我按天,小时和秒创建倒数计时器。我现在将它们存储在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上构建的。我想将它打印到{{1>}方法中单元 View Controller中的标签

1 个答案:

答案 0 :(得分:2)

将您的倒计时时间(以秒为单位)保存在名为countdown的单个变量中:

var countdown = 7202 // two hours and two seconds

到了显示它时,将其分为hoursminutesseconds,然后使用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