我正在尝试在Swift中设置一个倒计时器。当计时器结束时,会出现一个重新启动按钮,我想重新启动计时器。
这是目前为止我的代码。
class TimerViewController: UIViewController {
let duration: Double = 5 // duration in seconds
var timer: Timer?
var progressView: UIProgressView!
var timeElapsed: Double = 0
override func viewDidLoad() {
super.viewDidLoad()
// Create the progress view
progressView = UIProgressView(progressViewStyle: .default)
progressView.frame = CGRect(x: 20, y: 100, width: view.frame.width - 40, height: 10)
progressView.progress = 0
view.addSubview(progressView)
// Create the timer
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true)
}
@objc func timerFired() {
timeElapsed += 0.01
let progress = Float(timeElapsed / duration)
progressView.progress = progress
if timeElapsed >= duration {
timer?.invalidate()
timerEnded()
}
}
func timerEnded() {
// Timer has ended, do something here
// Show the restart button
print("Ended")
let restartButton = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
restartButton.setTitle("Restart", for: .normal)
restartButton.addTarget(self, action: #selector(restartTimer), for: .touchUpInside)
view.addSubview(restartButton)
}
@objc func restartTimer() {
// Restart the timer
timeElapsed = 0
progressView.progress = 0
timer?.invalidate()
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true)
}
}
问题是计时器进度条显示良好,但未显示重启按钮。
1条答案
按热度按时间g6ll5ycj1#
你可能已经想明白了,但如果你没有,我相信按钮是在那里,只是你看不到它。设置一个背景颜色,你应该可以看到按钮
在
timerEnded
按钮中设置按钮标题后添加以下语句restartButton.backgroundColor = .gray
看看这个有没有帮助。