Xcode Swift 秒表应用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29832159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Xcode Swift Stopwatch App
提问by ChallengerGuy
I have a stopwatch app I'm making that currently shows the minutes, seconds and milliseconds on a UILabel. It has a 'Start' button and a 'Stop' button. The code is below. How do I add hours to it? Also how do I make it continue where it was, when I stopped it? Currently if I press start again, it resets and starts over. I'll add a reset button later.
我有一个正在制作的秒表应用程序,它目前在 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)”
}
采纳答案by cmashinho
回答by Pham Ngoc Quynh
To make continues to count on the stopwatch:
继续依靠秒表:
Create var stopTime : NSTimeInterval = 0
创建 var stopTime : NSTimeInterval = 0
When stop() function is called, insert this code:
当调用 stop() 函数时,插入以下代码:
stopTime = elapsedTime
In start() function, replace to:
在 start() 函数中,替换为:
elapsedTime = (currentTime - startTime) + stopTime
Or You can use NSDate(), NSDateFormatter() to solve this problem. Reference here enter link description here
或者你可以使用 NSDate(), NSDateFormatter() 来解决这个问题。参考这里输入链接描述这里