gpt4 book ai didi

ios - 秒表超过 60 分钟

转载 作者:行者123 更新时间:2023-11-28 11:22:17 25 4
gpt4 key购买 nike

抱歉,如果这听起来像是一个菜鸟问题。我正在为 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)"



}

秒发生了什么而分钟没有发生?

最佳答案

你的线路

let minutes = UInt8(elapsedTime/60)

计算总分钟数,而不是“一小时内”的分钟数。您可以稍后通过减去 60 * 小时 来解决这个问题。

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

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)

关于ios - 秒表超过 60 分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26702874/

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