欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Swift实现iOS应用中短信验证码倒计时功能的实例分享

程序员文章站 2023-11-28 22:16:58
在开始之前,我们先来了解一个概念 属性观测器(property observers): 属性观察器监控和响应属性值的变化,每次属性被设置值的时候都会调用属性观察器,甚至新...

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

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

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

  • willset在新的值被设置之前调用
  • didset在新的值被设置之后立即调用

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

Swift实现iOS应用中短信验证码倒计时功能的实例分享

首先声明一个发送按钮:

复制代码 代码如下:

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 <= 0 {
            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
}

完成!