
要实现,点击 发送验证码 后,显示倒计时的60秒,每秒数字变化减少1。
搜:
swift click button count down
Swift NSTimer Tutorial – Lets create a Swift Timer (counter) application – iOS-Blog
最后代码如下:
    let countdownTotalNum:Int = 60     var countdownCurNum:Int = 0     var countdownTimer:NSTimer startCountdown()     func startCountdown() {         print("startCountdown")         self.countdownCurNum = self.countdownTotalNum         updateCountdownLabel()         self.countdownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector:Selector("updateCountdown"), userInfo: nil, repeats: true)     }     func updateCountdown() {         print("updateCountdown self.countdownCurNum=\(self.countdownCurNum)")         self.countdownCurNum -= 1         if self.countdownCurNum <= 0 {             self.countdownTimer.invalidate()             self.countdownCurNum  = 0         }         updateCountdownLabel()     }     func updateCountdownLabel(){         print("updateCountdownLabel self.countdownCurNum=\(self.countdownCurNum)")         dispatch_async(dispatch_get_main_queue(), { () -> Void in             if self.countdownCurNum == 0 {                 self.verifySmsCodeButton.setTitle(self.strSendVerifyCode, forState:UIControlState.Normal)                 self.verifySmsCodeButton.enabled = true             }else if self.countdownCurNum > 0 {                 self.verifySmsCodeButton.setTitle(String(self.countdownCurNum) + " 秒", forState:UIControlState.Normal)                 self.verifySmsCodeButton.enabled = false             }         })     }     func stopCountdown(){         print("stopCountdown: self.countdownCurNum=\(self.countdownCurNum)")         self.countdownTimer.invalidate()         self.countdownCurNum = 0         updateCountdownLabel()     }  | 
效果:

点击后开始倒计时:

转载请注明:在路上 » [已解决]swift实现点击按钮后显示倒计时