繁体   English   中英

如何快速重启计时器

[英]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)
    }
}

我想在用户单击“重新发送”按钮时重新启动计时器,并希望在用户单击“验证”按钮时执行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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM