Swift如何实现iOS应用中短信验证码倒计时功能

来源:爱站网时间:2021-01-23编辑:网友分享
短信验证码倒计时功能是不是很多用户们都非常的好奇呢?那么这个功能要怎样才能实现?那么接下来我们就一起去看看Swift如何实现iOS应用中短信验证码倒计时功能的内容。

短信验证码倒计时功能是不是很多用户们都非常的好奇呢?那么这个功能要怎样才能实现?那么接下来我们就一起去看看Swift如何实现iOS应用中短信验证码倒计时功能的内容。

在开始之前,我们先来了解一个概念 属性观测器(Property Observers):

属性观察器监控和响应属性值的变化,每次属性被设置值的时候都会调用属性观察器,甚至新的值和现在的值相同的时候也不例外。

可以为属性添加如下的一个或全部观察器:

  • willSet在新的值被设置之前调用
  • didSet在新的值被设置之后立即调用

接下来开始我们的教程,先展示一下最终效果:

2016418144945893.gif (372×180)

首先声明一个发送按钮:

 

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 {
        sendButton.setTitle("验证码已发送(\(newValue)秒后重新获取)", forState: .Normal)

 

        if newValue             sendButton.setTitle("重新获取验证码", forState: .Normal)
            isCounting = false
        }
    }
}


当remainingSeconds变化时更新sendButton的显示文本。

 

倒计时的功能我们用NSTimer实现,先声明一个NSTimer实例:

 

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.grayColor()
        } else {
            countdownTimer?.invalidate()
            countdownTimer = nil

            sendButton.backgroundColor = UIColor.redColor()
        }

        sendButton.enabled = !newValue
    }
}


同样,我们给isCounting添加一个willSet方法,当isCounting的newValue为true时,我们通过调用NSTimer的类方法
scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:创建并启动刚才声明的countdownTimer实例,这个实例每一秒钟调用一次updateTime:方法:

 

 

 


func updateTime(timer: NSTimer) {
     // 计时开始时,逐秒减少remainingSeconds的值
    remainingSeconds -= 1
}


当isCounting的newValue为false时,我们停止countdownTimer并将countdownTimer设置为nil。

 

此外我们还设置了倒计时的时间(这里为了演示时间设置为5秒)和发送按钮在不同isCounting状态下的样式(这里调整了背景色)和是否可点击。

最后实现sendButtonClick:方法,这个方法在点击sendButton时调用:

 

 func sendButtonClick(sender: UIButton) {
    // 启动倒计时
    isCounting = true
}


完成!

 

上文就是关于Swift如何实现iOS应用中短信验证码倒计时功能的内容,希望大家喜欢我的教程,并且能从中得到帮助。咱们下次实例再会。

 

上一篇:iOS自定义alertView提示框的代码

下一篇:iOS远程推送的实现代码

您可能感兴趣的文章

相关阅读

热门软件源码

最新软件源码下载