swift 如何使重新启动按钮出现时,计时器结束在斯威夫特?

tf7tbtn2  于 2023-01-12  发布在  Swift
关注(0)|答案(1)|浏览(160)

我正在尝试在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)
    }
}

问题是计时器进度条显示良好,但未显示重启按钮。

g6ll5ycj

g6ll5ycj1#

你可能已经想明白了,但如果你没有,我相信按钮是在那里,只是你看不到它。设置一个背景颜色,你应该可以看到按钮
timerEnded按钮中设置按钮标题后添加以下语句
restartButton.backgroundColor = .gray
看看这个有没有帮助。

相关问题