如何在 swift 中重新启动计时器

how to restart the timer in swift

我正在制作一个使用 OTP 屏幕的应用程序。我锻炼了计时器功能,还能够更改文本并再次显示计时器。我的问题是我无法再次重新启动计时器。它卡在 00:10.

下面是我的代码,请大家帮忙!!

@IBOutlet weak var butttonName: ButtonDesign!
var countTimer:Timer!
var counter = 10
var restartTimer = false
var isTimerRunning = false

override func viewDidLoad() {
if isTimerRunning == false {
        startTimer()}
}

func startTimer() {
self.countTimer = Timer.scheduledTimer(timeInterval: 1 , target: self, selector: #selector(OTPVerificationViewController.changeTitle), userInfo: nil, repeats: true)
isTimerRunning = true
}
@objc func changeTitle()
{
    if counter != 0
    {
        butttonName.setTitle(timeString(time: TimeInterval(counter)), for: .normal)
        counter -= 1
        butttonName.isEnabled = false

    }  else {
        countTimer.invalidate()
        butttonName.setTitle("Resend", for: .normal)
    }
}

@IBAction func verifyButton(_ sender: UIButton) {
if butttonName.currentTitle == "Resend" {
        print("clicked when name is resend !!!")
        if restartTimer == true {
            startTimer()
            restartTimer = false
        }
    } else {
        print("clicked when it is name is verify")
        self.performSegue(withIdentifier: "confirmPassword", sender: self)
    }
}

我想在用户单击 "Resend" 按钮时重新启动计时器,并希望在用户单击 "Verify" 按钮时执行 segue。两个按钮都是同一个按钮,我正在 运行 时间

更改名称

你也需要重启计数器

if butttonName.currentTitle == "Resend" {
   counter = 10
   // startTimer()
}

方法如下:

 var count = 120
func updateCounter(){
    if #available(iOS 10.0, *) {
        Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { (timer) in
            if(self.count > 0){
                self.lblTime.text = "\(self.count)"
                self.count = self.count-1
            }else {
                self.lblTime.text =  "0"
                timer.invalidate()
                self.btnresend.isHidden = false // in your case you can change the title of the button
            }
        })
    } else {
        // Fallback on earlier versions
        Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.timerMethod), userInfo: nil, repeats: true)
    }
}

@objc func timerMethod() {
    if(self.count > 0){
        self.lblTime.text = "\(self.count)"
        self.count = self.count-1
    }else {
        self.lblTime.text =  "0:0"
        self.btnresend.isHidden = false
    }
}

从你想重新开始计时的地方调用更新计数器方法

设置计数 120 或者您想要

self.count = 120