在开始之前,我们先来了解一个概念 属性观测器(Property Observers):
属性观察器监控和响应属性值的变化,每次属性被设置值的时候都会调用属性观察器,甚至新的值和现在的值相同的时候也不例外。
可以为属性添加如下的一个或全部观察器:
接下来开始我们的教程,先展示一下最终效果:
首先声明一个发送按钮:
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.redColor() sendButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) sendButton.setTitle("获取验证码", forState: .Normal) sendButton.addTarget(self, action: "sendButtonClick:", forControlEvents: .TouchUpInside)
self.view.addSubview(sendButton) }
var remainingSeconds = 0
var remainingSeconds: Int = 0 { willSet { sendButton.setTitle("验证码已发送(\(newValue)秒后重新获取)", forState: .Normal)if newValue <= 0 { sendButton.setTitle("重新获取验证码", forState: .Normal) isCounting = false } } }
倒计时的功能我们用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 } }
func updateTime(timer: NSTimer) { // 计时开始时,逐秒减少remainingSeconds的值 remainingSeconds -= 1 }
此外我们还设置了倒计时的时间(这里为了演示时间设置为5秒)和发送按钮在不同isCounting状态下的样式(这里调整了背景色)和是否可点击。
最后实现sendButtonClick:方法,这个方法在点击sendButton时调用:
func sendButtonClick(sender: UIButton) { // 启动倒计时 isCounting = true }
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。