gpt4 book ai didi

ios - Swift 中 for 循环中的计时器

转载 作者:行者123 更新时间:2023-11-28 12:42:09 25 4
gpt4 key购买 nike

我只想在给定循环次数的循环内运行计时器。还有一个外环。

用户将输入他想要重复多少次,每次重复多少次计数,两次计数之间的时间间隔。

应用程序将显示每次重复的次数。完成所有重复后,应用程序将停止计时器。

但是我觉得很难。看起来 timer 忽略了 for 循环,它本身就是一个循环,当我们仅发出 timer.invalidate() 时停止。

有什么想法吗?

for x in 0...HowManyRepetitions {

counter = 0
CountLabel.text = "\(counter)"
RepetitionLabel.text = "\(x) / \(HowManyRepetitions)"

for y in 0...HowManyCounts {

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

}

}

最佳答案

需要在计时器处理程序中管理重复计数。

您通常将计时器作为实例属性。 (您可能需要使计时器无效,例如,当 viewWillDisappear(_:) 时。)

所以,你可能需要在类里面写这样的东西:

var timer: NSTimer?
func startTimer(howManyCounts: Int, periodBetween: NSTimeInterval) {
let userInfo: NSMutableDictionary = [
"counter": 0,
"howManyCounts": howManyCounts,
"myName": "Timer"
]
self.timer = NSTimer.scheduledTimerWithTimeInterval(periodBetween, target: self, selector: #selector(timerHandler), userInfo: userInfo, repeats: true)
}

@objc func timerHandler(timer: NSTimer) {
guard let info = timer.userInfo as? NSMutableDictionary else {
return
}
var counter = info["counter"] as? Int ?? 0
let howManyCounts = info["howManyCounts"] as? Int ?? 0
let myName = info["myName"] as? String ?? "Timer"
counter += 1

print("\(myName):\(counter)") //countLabel.text = "\(counter)"

if counter >= howManyCounts {
timer.invalidate()
} else {
info["counter"] = counter
}
}

从与以下相同类的方法中的某处启动计时器:

    startTimer(10, periodBetween: 3.0)

我不明白为什么你需要外循环,但如果你想让多个定时器工作,你需要保留所有定时器。

var timers: [NSTimer] = []
func startTimers(howManyRepetitions: Int, howManyCounts: Int, periodBetween: NSTimeInterval) {
timers = []
for x in 1...howManyRepetitions {
let userInfo: NSMutableDictionary = [
"counter": 0,
"howManyCounts": howManyCounts,
"myName": "Timer-\(x)"
]
timers.append(NSTimer.scheduledTimerWithTimeInterval(periodBetween, target: self, selector: #selector(timerHandler), userInfo: userInfo, repeats: true))
}
}

启动计时器为:

    startTimers(3, howManyCounts: 4, periodBetween: 1.0)

关于ios - Swift 中 for 循环中的计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39188113/

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