gpt4 book ai didi

ios - 如何在 swift 中使用完成处理程序制作倒数计时器

转载 作者:搜寻专家 更新时间:2023-10-31 21:52:15 25 4
gpt4 key购买 nike

目前我正在尝试创建一个 3...2...1... 开始吧! Go 之后的倒计时类型!说明发生了一个 Action ,但是根据我的理解,使用 Timer.scheduleTimer 的完成处理程序的选项没有能力倒计时?

截至目前,我可以从 3 开始倒数,但不知道如何在 Go 中使计时器无效!并执行一个 Action

var seconds = 3
var countDownTimer = Timer()

func startCountDown() {
countDownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(TrackActivityVC.updateTimer), userInfo: nil, repeats: true)
}

func updateTimer() {

seconds -= 1
print(seconds)
}

// Not sure how to use this code to create a countdown, as it doesn't seem possible with this method

Timer.scheduledTimer(withTimeInterval: someInterval, repeats: false) {

}

因此问题是如何使用完成处理程序制作倒数计时器。

最佳答案

以下是如何使用尾随闭包语法创建倒数计时器:

var seconds = 3

Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
self.seconds -= 1
if self.seconds == 0 {
print("Go!")
timer.invalidate()
} else {
print(self.seconds)
}
}

这是一个更好的版本,它在 viewController 被取消初始化时使计时器无效。它使用 [weak self] 来避免在关闭时卡在 viewController 上:

class MyViewController: UIViewController {
var seconds = 3
var myTimer: Timer?

func startCountdown() {
myTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] timer in
self?.seconds -= 1
if self?.seconds == 0 {
print("Go!")
timer.invalidate()
} else if let seconds = self?.seconds {
print(seconds)
}
}
}

deinit {
// ViewController going away. Kill the timer.
myTimer?.invalidate()
}
}

关于ios - 如何在 swift 中使用完成处理程序制作倒数计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44857105/

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