在开始之前,我们先来了解一个概念 属性观测器(Property Observers):
属性观察器监控和响应属性值的变化,每次属性被设置值的时候都会调用属性观察器,甚至新的值和现在的值相同的时候也不例外。
可以为属性添加如下的一个或全部观察器:
- willSet在新的值被设置之前调用
-
didSet在新的值被设置之后立即调用
接下来开始我们的教程,先展示一下最终效果:
首先声明一个发送按钮:
复制代码
var sendButton: UIButton!
在viewDidLoad方法中给发送按钮添加属性:
复制代码
override func viewDidLoad() {
super.viewDidLoad()sendButton = UIButton()
sendButton.frame = CGRect(x: 40, y: 100, width: view.bounds.width - 80, height: 40)
sendButton.backgroundColor = UIColor.redColor()
sendButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
sendButton.setTitle("获取验证码", forState: .Normal)
sendButton.addTarget(self, action: "sendButtonClick:", forControlEvents: .TouchUpInside)self.view.addSubview(sendButton)
}
接下来声明一个变量remainingSeconds代表当前倒计时剩余的秒数:
复制代码
var remainingSeconds = 0
我们给remainingSeconds添加一个willSet方法,这个方法会在remainingSeconds的值将要变化的时候调用,并把值传递给参数newValue:
复制代码
var remainingSeconds: Int = 0 {
willSet {











