您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

Swift 實作短信驗證碼倒計時:用屬性觀測器讓程式碼更乾淨

編輯:iOS 相關教學

用 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)
}

二、用 willSet 驅動倒數文字

var remainingSeconds: Int = 0 {
    willSet {
        sendButton.setTitle("驗證碼已發送(\(newValue)秒後重新獲取)", for: .normal)
        if newValue <= 0 {
            sendButton.setTitle("重新獲取驗證碼", for: .normal)
            isCounting = false
        }
    }
}

每次 remainingSeconds 變動,willSet 就會拿到即將寫入的新值並更新按鈕標題;倒數歸零時順手把計時開關關掉。

三、用 isCounting 控制計時器的開關

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() 避免計時器殘留。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved