如何快速重启计时器

时间:2018-07-02 12:29:51

标签: ios swift nstimer

我正在做一个我使用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。两个按钮都相同我正在运行时更改名称

2 个答案:

答案 0 :(得分:0)

您也需要重新启动计数器

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

答案 1 :(得分:0)

只需按照以下方法进行操作即可:

 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