聲明一個(gè)計(jì)時(shí)器
fikeprivate var countdownTimer: Timer?
計(jì)時(shí)剩余秒數(shù)
fileprivate var remainingSeconds: Int =0 {will Set {
UIView.beginAnimations(nil, context:nil)
UIView.setAnimationDuration(1)
self.getCodeBtn.setTitle("\(newValue)秒", for:UIControlState.normal)
UIView.commitAnimations()
ifnewValue <=0{
getCodeBtn.isEnabled=true
getCodeBtn.setTitle("重發(fā)驗(yàn)證碼", for:UIControlState.normal)
}
? ? ? }
}
聲明一個(gè)變量來開關(guān)計(jì)時(shí)器
fileprivate var isCounting =false{
willSet{
ifnewValue {
countdownTimer=Timer.scheduledTimer(timeInterval:1, target:self, selector:#selector(RegisterViewController.updateTime), userInfo:nil, repeats:true)
remainingSeconds=60
}else{
getCodeBtn.isEnabled=true
countdownTimer?.invalidate()
countdownTimer=nil
}
getCodeBtn.isEnabled=!newValue
}
}
@objc fileprivate func updateTime(){
remainingSeconds=remainingSeconds-1
}