定时器Timer

self.codeBtn.addTarget(self, action: #selector(createTimer), for: .touchUpInside)

    func createTimer() {
        self.codeBtn.setTitle("5", for: .normal)
        self.codeBtn.isUserInteractionEnabled = false
        
        self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerReduces), userInfo: nil, repeats: true)
        self.timer?.fire()
    }
    func timerReduces() {
        self.startTime -= 1
        let time = "\(self.startTime)"
        self.codeBtn.setTitle(time, for: .normal)
        print(self.startTime)
//        let newStr = NSString(string: time)
//        let num = newStr.intValue
        if self.startTime == 0 {
            self.codeBtn.isUserInteractionEnabled = true
            self.codeBtn.setTitle("重新获取验证码", for: .normal)
            self.timer?.invalidate()
            self.startTime = 5
        }
    }

你可能感兴趣的:(定时器Timer)