1.定義全局
var timer = NSTimer?()
var count = 10
var btn = UIButton()
2.在viewDidLoad里實(shí)現(xiàn)
btn.frame = CGRectMake(100, 100, 110, 40)
btn.backgroundColor = UIColor.orangeColor()
btn.addTarget(self, action: #selector(ViewController.btnClicked), forControlEvents: .TouchUpInside)
btn.setTitle("獲取", forState: UIControlState.Normal)
self.view.addSubview(btn)
func btnClicked() {
count = 10
btn.enabled = false
btn.backgroundColor = UIColor.lightGrayColor()
btn.setTitle("倒計(jì)時(shí)(\(count)秒)", forState: .Normal)
//? ? ? ? 啟動(dòng)定時(shí)器
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ViewController.tickDown), userInfo: nil, repeats: true)
//? ? ? ? 如果要停止定時(shí)器,調(diào)用NSTimer的invalidate()方法即可
//? ? ? ? timer.invalidate()
}
func tickDown() {
count -= 1
btn.setTitle("倒計(jì)時(shí)(\(count)秒)", forState: .Normal)
if (count==0) {
timer!.invalidate()
timer = nil
btn.setTitle("獲取", forState: UIControlState.Normal)
btn.enabled = true
btn.backgroundColor = UIColor.orangeColor()
}
print(count)
}