gpt4 book ai didi

arrays - Swift countDown 定时器逻辑

转载 作者:搜寻专家 更新时间:2023-11-01 07:29:43 26 4
gpt4 key购买 nike

我正在创建一个按天、小时和秒计算的倒数计时器。我目前将它们存储在 String 数组中,同时还将它们转换为 Int(使用 map() ),以便在将值放入标签时可以倒计时/递减。

打印到日志时的当前输出是:["[68168]", "[68188]", "[68243]", "[68281]"]

我在形成倒计时函数的逻辑时遇到问题,因此当秒数达到“0”时,1 分钟下降,59 分钟后 1 小时递减,等等,直到它达到“00:00:00 ”。

在每个索引中,我有 [Hour, Minute, Second] 的 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”

附言,这是建立在 TableViewController 上的。 我想将其打印到 cellForRowAtIndexPath 中的 cell View Controller 中的标签。方法

最佳答案

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

var countdown = 7202 // two hours and two seconds

当需要显示时,将其分成小时分钟,并使用String(格式:) 格式化它的构造函数:

// 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:0202:00:0102:00:0001:59:5901:59:58

If you have more than one timer, keep them in an array:

// 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:5900:01:0100:16:4001:01:0103:25:45

关于arrays - Swift countDown 定时器逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33393874/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com