在開始之前,我們先來了解一個概念 屬性觀測器(Property Observers):
屬性觀察器監控和響應屬性值的變化,每次屬性被設置值的時候都會調用屬性觀察器,甚至新的值和現在的值相同的時候也不例外。
可以為屬性添加如下的一個或全部觀察器:
接下來開始我們的教程,先展示一下最終效果:
首先聲明一個發送按鈕:
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)
}
if newValue <= 0 {
sendButton.setTitle("重新獲取驗證碼", forState: .Normal)
isCounting = false
}
}
}
倒計時的功能我們用NSTimer實現,先聲明一個NSTimer實例:
remainingSeconds = 10
sendButton.backgroundColor = UIColor.grayColor()
} else {
countdownTimer?.invalidate()
countdownTimer = nil
sendButton.backgroundColor = UIColor.redColor()
}
sendButton.enabled = !newValue
}
}
此外我們還設置了倒計時的時間(這里為了演示時間設置為5秒)和發送按鈕在不同isCounting狀態下的樣式(這里調整了背景色)和是否可點擊。
最后實現sendButtonClick:方法,這個方法在點擊sendButton時調用:
新聞熱點
疑難解答