ios發送短信驗證碼計時器的swift實現

轉載自:http://www.jianshu.com/p/024dd2d6e6e6#

Update: Xcode 8.2.1 Swift 3

先介紹一下 屬性觀測器(Property Observers)

屬性觀察器監控和響應屬性值的變化,每次屬性被設置值的時候都會調用屬性觀察器,甚至新的值和現在的值相同的時候也不例外。

可以爲屬性添加如下的一個或全部觀察器:

  • willSet在新的值被設置之前調用
  • didSet在新的值被設置之後立即調用

摘錄來自: 極客學院. “The Swift Programming Language 中文版”。 iBooks.

接下來開始我們的教程,先展示一下最終效果:


SMSScreenshot.gif

首先聲明一個發送按鈕:

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.red
    sendButton.setTitleColor(UIColor.white, for: .normal)
    sendButton.setTitle("獲取驗證碼", for: .normal)
    sendButton.addTarget(self, action: #selector(ViewController.sendButtonClick(_:)), for: .touchUpInside)

    self.view.addSubview(sendButton)
}

接下來聲明一個變量remainingSeconds代表當前倒計時剩餘的秒數:

var remainingSeconds = 0

我們給remainingSeconds添加一個willSet方法,這個方法會在remainingSeconds的值將要變化的時候調用,並把值傳遞給參數newValue:

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

        if newValue <= 0 {
            sendButton.setTitle("重新獲取驗證碼", forState: .normal)
            isCounting = false
        }
    }
}

remainingSeconds變化時更新sendButton的顯示文本。

倒計時的功能我們用Timer實現,先聲明一個Timer實例:

var countdownTimer: Timer?

然後我們聲明一個變量來開啓和關閉倒計時:

var isCounting = false {
    willSet {
        if newValue {
            countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.updateTime(_:)), userInfo: nil, repeats: true)

            remainingSeconds = 10
            sendButton.backgroundColor = UIColor.gray
        } else {
            countdownTimer?.invalidate()
            countdownTimer = nil

            sendButton.backgroundColor = UIColor.red
        }

        sendButton.enabled = !newValue
    }
}

同樣,我們給isCounting添加一個willSet方法,當isCountingnewValuetrue時,我們通過調用Timer的類方法
scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:創建並啓動剛纔聲明的countdownTimer實例,這個實例每一秒鐘調用一次updateTime:方法:

func updateTime(timer: Timer) {
     // 計時開始時,逐秒減少remainingSeconds的值
    remainingSeconds -= 1
}

isCountingnewValuefalse時,我們停止countdownTimer並將countdownTimer設置爲nil

此外我們還設置了倒計時的時間(這裏爲了演示時間設置爲5秒)和發送按鈕在不同isCounting狀態下的樣式(這裏調整了背景色)和是否可點擊。

最後實現sendButtonClick:方法,這個方法在點擊sendButton時調用:

 func sendButtonClick(sender: UIButton) {
    // 啓動倒計時
    isCounting = true
}

完成!

Github地址:
https://github.com/GuiminChu/JianshuExample/tree/master/SMSSendButtonExample



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章