我正在获取以秒为单位存储在 Int 数组中的时间值,并尝试将其放在 UILabel 上,然后由 countDown 函数触发倒计时。我无法获得每个单元格中倒计时的时间,也无法在不获取原始秒值而不对其进行格式化的情况下打印数组,如下所示。目前我只能在每个单元格的 UILabel 上显示原始值:6532
(小时、分钟、秒)
当我尝试在 for 循环
中单独打印数组时,我也无法格式化该数组,如下所示。该数组存储为 Int。
在 countDown 函数中使用 for 循环时,我可以将时间格式打印到日志中:HH:MM:SS
。但并非如此。
这是我的倒计时函数:
func countDown() {
//timerInt is an array where I'm storing the Int values.
for i in 0 ..< timerInt.count {
let hours = timerInt[i] / 3600
let minsec = timerInt[i] % 3600
let minutes = minsec / 60
let seconds = minsec % 60
print(String(format: "%02d:%02d:%02d", hours, minutes, seconds))
timerInt[i]--
print(self.timerInt[i])
}
}
我正在尝试在 cellForRowAtIndexPath 方法中执行此操作。 UILabel 位于一个单独的类中:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! cell
//This is the first item i'm posting on a UILabel and it works fine.
myCell.productName.text = productName[indexPath.row]
/*This cell/label I'm unable to format like in the for loop
which is formatted as a string*/
myCell.secondLabel.text = ("\(intArray[indePath.row])")
/*how do I format the intArray here so that the time
appears HH:MM:SS?? */
return myCell
}
如何格式化 intArray
以便将其以格式化时间 (HH:MM:SS) 打印到日志和 UI,就像在 for 循环
中一样当我使用字符串格式化程序打印到日志时?
非常感谢任何帮助!
最佳答案
您需要创建一个函数,将秒转换为格式化字符串,如
func formattedTime(seconds: Int = 0) -> String {
let hours = seconds/3600
let minsec = seconds%3600
let minutes = minsec / 60
let seconds = minsec % 60
return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
}
一旦你有了这个方法,你就可以在你的 countDown
方法中使用这个方法以及 cellForRowAtIndexPath
func countDown() {
//timerInt is an array where I'm storing the Int values.
for i in 0 ..< timerInt.count {
print(formattedTime(timerInt[i]))
timerInt[i]--
print(self.timerInt[i])
}
}
在 cellForRowAtIndexPath
中,您将 timerInt
作为 Int
数组,其中每个索引值需要显示在单元格 UILabel
上>
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! cell
//This is the first item i'm posting on a UILabel and it works fine.
myCell.productName.text = productName[indexPath.row]
/*This cell/label I'm unable to format like in the for loop
which is formatted as a string*/
myCell.secondLabel.text = ("\(intArray[indePath.row])")
/*how do I format the intArray here so that the time
*/appears HH:MM:SS??
print(self.formattedTime(self.intArray[indePath.row]))
return myCell
}
关于arrays - 在 cellForRowAtIndexPath Swift 中将 Int Array 格式化为 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33401134/