【问题标题】:Xcode Swift Stopwatch AppXcode Swift 秒表应用
【发布时间】:2015-04-23 19:01:48
【问题描述】:

我正在制作一个秒表应用程序,它目前在 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)”

}

【问题讨论】:

  • 请使用code blocks 来描述您的问题,而不是包含您的代码截图。这使得复制和粘贴成为可能。您还可以配置highlighting of your code
  • 好的,抱歉,谢谢!

标签: ios xcode swift timer


【解决方案1】:

你可以这样计算小时数

elapsedtime / 3600

阅读更多NSTimeInterval to HH:mm:ss?

【讨论】:

  • 非常感谢。你知道如何让它继续计数秒表而不是在我再次点击开始时重置吗?
  • @ChallengerGuy 请给我发电子邮件
  • 我该怎么做?我对整个堆栈溢出的事情很陌生。
【解决方案2】:

要让秒表继续计数:

创建var stopTime : NSTimeInterval = 0

调用 stop() 函数时,插入以下代码:

 stopTime = elapsedTime

在 start() 函数中,替换为:

elapsedTime = (currentTime - startTime) + stopTime

或者你可以使用 NSDate(), NSDateFormatter() 来解决这个问题。 参考这里enter link description here

【讨论】:

    猜你喜欢
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 2015-07-13
    • 2018-04-29
    • 1970-01-01
    • 2020-08-10
    相关资源
    最近更新 更多