gpt4 book ai didi

ios - 仅以秒为单位的倒计时(表格 00 :20 to 0) using NSTimer

转载 作者:行者123 更新时间:2023-11-29 01:57:50 24 4
gpt4 key购买 nike

我需要一个从 20 秒到 0 的标签倒计时,然后重新开始。这是我第一次在 Swift 中做项目,我正在尝试使用 NSTimer.scheduledTimerWithTimeInterval。此倒计时应循环运行给定的次数。

我很难实现开始再次开始 方法(循环)。我基本上找不到一种方法来启动时钟 20 秒,当它结束时,再次启动它。

如果有任何关于如何做到这一点的想法,我将不胜感激瓦格纳

 @IBAction func startWorkout(sender: AnyObject) {

timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("countDownTime"), userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()

}

func countDownTime() {

var currentTime = NSDate.timeIntervalSinceReferenceDate()

//Find the difference between current time and start time.
var elapsedTime: NSTimeInterval = currentTime - startTime

//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 strSeconds = seconds > 9 ? String(seconds):"0" + String(seconds)
let strFraction = fraction > 9 ? String(fraction):"0" + String(fraction)

//concatenate minuets, seconds and milliseconds as assign it to the UILabel
timeLabel.text = "\(strSeconds):\(strFraction)"
}

最佳答案

您应该将日期结束时间设置为距现在 20 秒,然后只检查日期 timeIntervalSinceNow。一旦 timeInterval 达到 0,您再次将其设置为 20 秒

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var strTimer: UILabel!

var endTime = Date(timeIntervalSinceNow: 20)
var timer = Timer()

@objc func updateTimer(_ timer: Timer) {
let remaining = endTime.timeIntervalSinceNow
strTimer.text = remaining.time
if remaining <= 0 {
endTime += 20
}
}

override func viewDidLoad() {
super.viewDidLoad()
strTimer.font = .monospacedSystemFont(ofSize: 20, weight: .semibold)
strTimer.text = "20:00"
timer = .scheduledTimer(timeInterval: 1/30, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
}

}

extension TimeInterval {
var time: String {
String(format: "%02d:%02d", Int(truncatingRemainder(dividingBy: 60)), Int((self * 100).truncatingRemainder(dividingBy: 100)))
}
}

关于ios - 仅以秒为单位的倒计时(表格 00 :20 to 0) using NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30652964/

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