定时器Timer

self.codeBtn.addTarget(self, action: #selector(createTimer), for: .touchUpInside)

    func createTimer() {
        self.codeBtn.setTitle("5", for: .normal)
        self.codeBtn.isUserInteractionEnabled = false
        
        self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerReduces), userInfo: nil, repeats: true)
        self.timer?.fire()
    }
    func timerReduces() {
        self.startTime -= 1
        let time = "\(self.startTime)"
        self.codeBtn.setTitle(time, for: .normal)
        print(self.startTime)
//        let newStr = NSString(string: time)
//        let num = newStr.intValue
        if self.startTime == 0 {
            self.codeBtn.isUserInteractionEnabled = true
            self.codeBtn.setTitle("重新获取验证码", for: .normal)
            self.timer?.invalidate()
            self.startTime = 5
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 问题原因: 一般定时器timer都会被以默认模式default添加到主线程的runloop中,当滑动界面时,run...
    SunnyLeong阅读 1,528评论 1 17
  • Timer是一种定时器工具,用来在一个后台线程计划执行指定任务。它可以计划执行一个任务一次或反复多次。TimerT...
    AiPuff阅读 11,973评论 0 2
  • 本文旨在总结项目中因使用各类定时器而踩到的坑,并附上经验总结。 NSTimer NSTimer是最常用的定时器,坑...
    QihuaZhou阅读 3,317评论 0 3
  • Timer 定时器相信都不会陌生,之所以拿它来做源码分析,是发现整个控制流程可以体现很多有意思的东西。 在业务开发...
    石先阅读 6,460评论 2 13
  • 像我这样独行的人, 在街头,在凌晨,在弄巷, 一杯酒来,一根烟, 抬头看天,低头看地,还有我自己。 39码的鞋,2...
    英姿飒爽俏公子阅读 329评论 5 5