Xcode Swift秒表应用

挑战者

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

}
卡马西尼奥

您可以计算小时数

elapsedtime / 3600

阅读更多关于HH:mm:ss的NSTimeInterval吗?

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章