用 Swift 寫驗證碼倒計時,可以比 Objective-C 更簡潔,關鍵在於「屬性觀測器」(Property Observers)。
屬性觀測器會監控並回應屬性值的變化,每次屬性被設定值時都會觸發——即使新值與舊值相同也一樣。可以為同一個屬性加上其中一個或兩個觀測器:
willSet:在新值被設定之前呼叫didSet:在新值被設定之後立即呼叫這代表我們不需要手動在每個地方呼叫「更新按鈕文字」,只要倒數秒數變了,UI 就會自動更新。

var sendButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
sendButton = UIButton()
sendButton.frame = CGRect(x: 40, y: 100, width: view.bounds.width - 80, height: 40)
sendButton.backgroundColor = UIColor.red
sendButton.setTitleColor(UIColor.white, for: .normal)
sendButton.setTitle("獲取驗證碼", for: .normal)
sendButton.addTarget(self, action: "sendButtonClick:", forControlEvents: .touchUpInside)
self.view.addSubview(sendButton)
}
var remainingSeconds: Int = 0 {
willSet {
sendButton.setTitle("驗證碼已發送(\(newValue)秒後重新獲取)", for: .normal)
if newValue <= 0 {
sendButton.setTitle("重新獲取驗證碼", for: .normal)
isCounting = false
}
}
}
每次 remainingSeconds 變動,willSet 就會拿到即將寫入的新值並更新按鈕標題;倒數歸零時順手把計時開關關掉。
var countdownTimer: NSTimer?
var isCounting = false {
willSet {
if newValue {
countdownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self,
selector: "updateTime", userInfo: nil, repeats: true)
remainingSeconds = 10
sendButton.backgroundColor = UIColor.gray
} else {
countdownTimer?.invalidate()
countdownTimer = nil
sendButton.backgroundColor = UIColor.red
}
sendButton.enabled = !newValue
}
}
開啟時建立每秒觸發一次的 NSTimer,同時把剩餘秒數設為 10、按鈕變灰並停用;關閉時則銷毀計時器、按鈕恢復紅色且可點擊。
func updateTime(timer: NSTimer) {
// 逐秒遞減,willSet 會自動接管 UI 更新
remainingSeconds -= 1
}
func sendButtonClick(sender: UIButton) {
// 啟動倒計時
isCounting = true
}
整個實作把「狀態」與「視覺」綁在一起:remainingSeconds 負責文字,isCounting 負責計時器與按鈕狀態,彼此透過屬性觀測器串接,不需要額外的更新程式碼。若要在正式專案使用,記得把倒數秒數改為 60,並在 viewDidDisappear 或 deinit 中呼叫 countdownTimer?.invalidate() 避免計時器殘留。