gpt4 book ai didi

ios - 如何在计时器运行时快速将秒数重置为零

转载 作者:行者123 更新时间:2023-11-28 05:32:51 24 4
gpt4 key购买 nike

<分区>

大家好,我用 Swift 做了一个简单的计时器。一切都很好,除了当秒数达到 59 秒而不是回到零时,他们只是继续前进。有人能指出我哪里出错了以及为什么会这样吗?

这是我的代码:-

class ViewController: UIViewController {

var startTime = NSTimeInterval()
var timer = NSTimer()
var isRunning = false

func updateTime() {

var currentTime = NSDate.timeIntervalSinceReferenceDate()

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)


//fraction of milliseconds

let fraction = UInt8(elapsedTime * 100)

//add the leading zero for minutues, seconds and milliseconds, store
// as string constants

let strMinutes = minutes > 9 ? String(minutes): "0" + String(minutes)

let strSeconds = seconds > 9 ? String(seconds): "0" + String(seconds)

let strFraction = fraction > 9 ? String(fraction): "0" + String(fraction)

//concatonate mins, seoncds and milliseconds, assign to UILable timercount

TimerCount.text = "\(strMinutes):\(strSeconds):\(strFraction)"

}



@IBOutlet weak var TimerCount: UILabel!


@IBAction func StartButton(sender: AnyObject) {

if !timer.valid {

let aSelector : Selector = "updateTime"

timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)

startTime = NSDate.timeIntervalSinceReferenceDate()
}

}


@IBAction func StopButton(sender: AnyObject) {

timer.invalidate()

}




@IBAction func ResetButton(sender: AnyObject) {

timer.invalidate()
TimerCount.text = "00:00:00"

}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com