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)"
}
在几分钟内没有发生的秒数会发生什么?
答案 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)