[英]Xcode Swift Stopwatch App
我有一个秒表应用程序,我正在制作,目前显示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)”
}
继续依靠秒表:
创建var stopTime : NSTimeInterval = 0
调用stop()函数时,插入以下代码:
stopTime = elapsedTime
在start()函数中,替换为:
elapsedTime = (currentTime - startTime) + stopTime
或者您可以使用NSDate(),NSDateFormatter()来解决此问题。 这里参考链接描述
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.