下面是我封裝好的一個(gè)Timer,語(yǔ)言:Swift3.0
import UIKit
class GHTimer: NSObject {
private var _timer:Timer!
/**
運(yùn)行中的狀態(tài)值
**/
private var _running = false
public var running:Bool {
get{
return _running
}
}
/**
暫停或停止的狀態(tài)值
**/
private var _isPause = true
public var isPause:Bool{
get{
return _isPause
}
}
/**
執(zhí)行的間隔時(shí)間(默認(rèn)3秒)
重新設(shè)置這個(gè)值之后需要重新啟動(dòng)timer
**/
public var intervalTime:Double = 3 {
willSet{
if intervalTime != newValue && _timer != nil {
if _running {
close()
}
_timer = Timer(timeInterval: TimeInterval(newValue), repeats: repeats, block: run)
}
}
}
/**
一直重復(fù)執(zhí)行(true)or執(zhí)行一次(false,默認(rèn))
重新設(shè)置這個(gè)值之后需要重新啟動(dòng)timer
**/
public var repeats:Bool = false {
willSet{
if repeats != newValue && _timer != nil {
if _running {
close()
}
_timer = Timer(timeInterval: TimeInterval(intervalTime), repeats: newValue, block: run)
}
}
}
/**
需要重復(fù)執(zhí)行的功能
**/
public var repeatRun:(()->Void)?
init(interval:Double, repeats:Bool, repeatRun: @escaping (()->Void)) {
self.intervalTime = interval
self.repeats = repeats
self.repeatRun = repeatRun
}
/**
啟動(dòng)timer
**/
public func start() {
if !_running {
_timer = Timer(timeInterval: TimeInterval(intervalTime), repeats: repeats, block: run)
RunLoop.current.add(_timer, forMode: .commonModes)
_running = true
_isPause = false
}
}
/**
關(guān)閉timer
**/
public func close() {
if _running {
_isPause = true
_running = false
_timer.invalidate()
_timer = nil
}
}
/**
停止或暫停timer
**/
public func stop() {
if _running && !_isPause {
_timer.fireDate = Date.distantFuture
_isPause = true
}
}
/**
從停止或暫停中恢復(fù)timer
**/
public func resume() {
if _running && _isPause {
_timer.fireDate = Date(timeIntervalSinceNow: intervalTime)
_isPause = false
}
}
private func run(timer:Timer) {
repeatRun?()
}
}
Example:
import UIKit
class ViewController: UIViewController {
var timer:GHTimer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let timeTimer = GHTimer(interval: 1, repeats: true, repeatRun: countTime)
timeTimer.start()
timer = GHTimer(interval: 2, repeats: true, repeatRun: run)
timer.start()
}
var count = 1
func countTime() {
print(count)
count = 1 + count % 5
}
func run() {
print("repeat: ", timer.intervalTime)
}
@IBAction func onClose(_ sender: UIButton) {
if timer.running{
print("close")
timer.close()
}else{
print("start")
timer.start()
}
}
@IBAction func onPause(_ sender: UIButton) {
if !timer.isPause {
print("pause")
timer.stop()
}else {
print("resume")
timer.resume()
}
}
@IBAction func onChangeInterval(_ sender: UIButton) {
print("change interval")
timer.intervalTime = 5
timer.start()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
源碼實(shí)踐:https://github.com/ghyh22/GHTimer