Swift4.0之Timer


Class Timer

A timer that fires after a certain time interval has elapsed, sending a specified message to a target object.

定时器类,到时间可以触发事件。一般在viewController或者UIView的代码中使用

1.定义一个定时器

var timer = Timer() //首先需要声明一个timer变量,一般声明为类的成员变量

2.定义一个定时器计时结束时,触发的处理方法。一定要在方法前加@objc

@objc func UpdateTimer() {

       //此处可以添加处理代码

    }

3.初始化并启动定时器的代码

timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ViewController.UpdateTimer), userInfo: nil, repeats: true)//这一句会同时启动计数器

 

解释一下Timer.scheduledTimer,这个方法的定义如下:

Timer.scheduledTimer(timeInterval: TimeInterval, target: Any, selector: Selector, userInfo: Any?, repeats: Bool)

timeInterval:是定时器触发间隔时间,上例中是0.1秒

target:是指定触发时处理方法, selector: #selector(ViewController.UpdateTimer)里的ViewController.UpdateTimer前面声明的UpdateTimer方法

userInfo:一般给nil就行了

repeats:如果是false,定时器只触发一次。如果要一直触发,请用true

4.停止计数器

timer.invalidate()


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM