Swift定时器

1.定义全局

var timer = NSTimer?()

var count = 10

var btn = UIButton()

2.在viewDidLoad里实现

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("倒计时(\(count)秒)", forState: .Normal)

//        启动定时器

timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ViewController.tickDown), userInfo: nil, repeats: true)

//        如果要停止定时器,调用NSTimer的invalidate()方法即可

//        timer.invalidate()

}

func tickDown() {

count -= 1

btn.setTitle("倒计时(\(count)秒)", forState: .Normal)

if (count==0) {

timer!.invalidate()

timer = nil

btn.setTitle("获取", forState: UIControlState.Normal)

btn.enabled = true

btn.backgroundColor = UIColor.orangeColor()

}

print(count)

}

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