在秒表中超过60分钟

时间:2014-11-02 18:35:23

标签: ios swift

抱歉,如果这听起来像一个菜鸟问题。我正在为iPhone制作一个秒表应用程序。标签显示hh:mm:ss。秒数在达到60时正确地重置为0,然后从0开始重新开始,但是分钟数超过60.这里是代码:

var elapsedTime = NSTimeInterval()

@IBAction func buttonAction(sender: AnyObject)
{
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "fireStopWatch", userInfo: nil, repeats: true)
    startTime = NSDate(timeIntervalSinceNow: 0)

}

func fireStopWatch()
   {
    var currentTime:NSDate = NSDate(timeIntervalSinceNow: 0)
    elapsedTime = currentTime.timeIntervalSinceDate(startTime)



    let minutes = UInt8(elapsedTime/60)
    elapsedTime -= (NSTimeInterval(minutes) * 60)
    let seconds = UInt8(elapsedTime)
    elapsedTime -= NSTimeInterval(seconds)
    let hours = UInt8(elapsedTime/3600.0)
    elapsedTime -= (NSTimeInterval(hours) * 3600)

    let strHours = hours > 9 ? String(hours):"0" + String(hours)
    let strMinutes = minutes > 9 ? String(minutes):"0" + String(minutes)
    let strSeconds = seconds > 9 ? String(seconds):"0" + String(seconds)


    displayTimeLabel.text = "\(strHours):\(strMinutes)"
    displaySecondsLabel.text = "\(strSeconds)"



}

在几分钟内没有发生的秒数会发生什么?

2 个答案:

答案 0 :(得分:2)

你的行

let minutes = UInt8(elapsedTime/60)

计算总分钟数,而不是分钟数"在一小时内#34;。 您可以稍后通过减去60 * hours来解决此问题。

但是我发现从最低单位(秒)开始然后计算更高的单位更容易 单位(分钟,小时......)使用整数除法和余数运算符 %

let totalSeconds = Int(elapsedTime)  // Total number of seconds as an integer
let seconds = totalSeconds % 60      // Seconds to display
let totalMinutes = totalSeconds / 60 // Total number of minutes
let minutes = totalMinutes % 60      // Minutes to display
let hours = totalMinutes / 60        // Hours to display

这也可以很容易地扩展到更多单位,例如几天。

请注意

let strHours = hours > 9 ? String(hours):"0" + String(hours)
let strMinutes = minutes > 9 ? String(minutes):"0" + String(minutes)
let strSeconds = seconds > 9 ? String(seconds):"0" + String(seconds)
displayTimeLabel.text = "\(strHours):\(strMinutes)"
displaySecondsLabel.text = "\(strSeconds)"
使用字符串格式化函数可以简化

displayTimeLabel.text = String(format: "%02d:%02d", hours, minutes)
displaySecondsLabel.text = String(format: "%02d", seconds)

答案 1 :(得分:1)

将小时数移到分钟以上,以便将其减去(就像你的分钟数超过秒数一样)

let hours = UInt8(elapsedTime/3600.0)
elapsedTime -= (NSTimeInterval(hours) * 3600)
let minutes = UInt8(elapsedTime/60)
elapsedTime -= (NSTimeInterval(minutes) * 60)
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)