Xcode Swift秒表应用程序

4

我正在制作一个秒表应用程序,目前它可以在UILabel上显示分钟、秒和毫秒。它有一个“开始”按钮和一个“停止”按钮。以下是代码。怎样才能添加小时?另外,如何使它在我停止后继续运行?当前,如果我再次按下开始按钮,它会重置并重新开始。稍后我会添加一个重置按钮。

//Variables
var startTime = NSTimeInterval()

//Start Button
@IBAction func start(sender: AnyObject) {
   let aSelector : Selector = “updateTime”
   timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
   startTime = NSDate.timeIntervalSinceReferenceDate()
}

//Stop Button
@IBAction func stop(sender: AnyObject) {
   timer.invalidate()
}

//Update Time Function
func updateTime() {

   var currentTime = NSDate.timeIntervalSinceReferenceDate()

   //Find the difference between current time and start time.

   var elapsedTime: NSTimeInterval = currentTime - startTime

   //calculate the minutes in elapsed time.

   let minutes = UInt8(elapsedTime / 60.0)

   elapsedTime -= (NSTimeInterval(minutes) * 60)

   //calculate the seconds in elapsed time.

   let seconds = UInt8(elapsedTime)

   elapsedTime -= NSTimeInterval(seconds)

   //find out the fraction of milliseconds to be displayed.

   let fraction = UInt8(elapsedTime * 100)

   //add the leading zero for minutes, seconds and millseconds and store them as string constants

   let strMinutes = String(format: "%02d", minutes)
   let strSeconds = String(format: "%02d", seconds)
   let strFraction = String(format: "%02d", fraction)

   //concatenate minuets, seconds and milliseconds as assign it to the UILabel

   displayTimeLabel.text = “\(strMinutes):\(strSeconds):\(strFraction)”

}

1
请使用代码块来描述您的问题,而不是包含代码截图。这样可以实现复制和粘贴等功能。您还可以配置代码高亮 - Álvaro Arranz
好的,抱歉和谢谢! - ChallengerGuy
2个回答

3

非常感谢。您知道如何使秒表继续计时,而不是在我再次点击“开始”时重置吗? - ChallengerGuy
@ChallengerGuy 请写邮件给我。 - cmashinho
我该怎么做?我对这个 Stack Overflow 的东西还很陌生。 - ChallengerGuy

0
为了让秒表继续计时:
创建 var stopTime : NSTimeInterval = 0 当调用 stop() 函数时,插入以下代码:
 stopTime = elapsedTime

在 start() 函数中,替换为:
elapsedTime = (currentTime - startTime) + stopTime

或者您可以使用NSDate()、NSDateFormatter()来解决这个问题。 参考链接 在此输入链接描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接