【发布时间】:2018-07-27 10:53:59
【问题描述】:
需要帮助来制作一个倒数计时器,直到它失效才能继续。它也不应该阻塞主线程。有什么建议吗?
private var currentCountdownSeconds = 3
private var countdownTimer = Timer()
private func performTimer() {
if secondsToCountDown != 0 {
print(secondsToCountDown)
countdownTimer = Timer(timeInterval: 1, target: self, selector: #selector(handleCountdown), userInfo: nil, repeats: true)
}
}
@objc private func handleCountdown() {
previewView.countdownLabel.text = "\(currentCountdownSeconds)"
currentCountdownSeconds -= 1
print(secondsToCountDown)
if secondsToCountDown == 0 {
countdownTimer.invalidate()
}
}
public func toggleMovieRecording() {
handleTimer()
videoCaptureLogic()
}
public func toggleCapturePhoto() {
handleTimer()
videoCaptureLogic()
}
【问题讨论】:
-
那么,你的代码有什么问题?
-
为什么你不直接给
countDownTimer = Timer(timeInterval: currentCountdownSeconds, target: self, selector: #selector(handleCountdown), userInfo: nil, repeats: true)并且在选择器被调用后让它失效? -
@AhmadF 代码执行没有错误,但是,我不知道如何让代码等到计时器失效才能继续执行另一行代码。
-
@RakeshaShastri ,我相信您的解决方案会使选择器每 3 秒调用一次。我需要每秒更新一次标签,让它看起来像一个倒数计时器。
-
只需将另一行代码放入
handleCountdown()方法中countdownTimer.invalidate()行之后
标签: swift timer block completion