话不多说,直接上代码!~
定时器
import UIKit
class XT_ZJTimer: NSObject {
private(set) var _timer: Timer!
fileprivate weak var _aTarget: AnyObject!
fileprivate var _aSelector: Selector!
var fireDate: Date {
get{
return _timer.fireDate
}
set{
_timer.fireDate = newValue
}
}
class func scheduledTimer(timeInterval ti: TimeInterval, target aTarget: AnyObject, selector aSelector: Selector, userInfo: Any?, repeats yesOrNo: Bool) -> XT_ZJTimer {
let timer = XT_ZJTimer()
timer._aTarget = aTarget
timer._aSelector = aSelector
timer._timer = Timer.scheduledTimer(timeInterval: ti, target: timer, selector: #selector(XT_ZJTimer.zj_timerRun), userInfo: userInfo, repeats: yesOrNo)
return timer
}
func fire() {
_timer.fire()
}
func invalidate() {
_timer.invalidate()
}
@objc func zj_timerRun() {
//如果崩在这里,说明你没有在使用Timer的VC里面的deinit方法里调用invalidate()方法
_ = _aTarget.perform(_aSelector)
}
deinit {
print("计时器已销毁")
}
}
需要调用的类封装
import UIKit
class XT_IntimateLoversTimer {
/// 活动结束秒数
var secondsToEnd: Int = 0
var myTimer: XT_ZJTimer!
var callBack: ((String)->())?
var isMin:Bool = false
init(seconds: Int, isMin:Bool, callBack: ((String)->())?) {
self.isMin = isMin
self.secondsToEnd = seconds
myTimer = XT_ZJTimer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerRun), userInfo: nil, repeats: true)
//如果希望对Timer做自定义的操作,使用_Timer属性
RunLoop.current.add(myTimer._timer, forMode: RunLoop.Mode.common)
myTimer.fire()
self.callBack = callBack
}
deinit {
myTimer.invalidate()
}
@objc func timerRun() {
secondsToEnd -= 1
if secondsToEnd == 0 {
myTimer.invalidate()
}
if isMin == true {
callBack?(minToTimeString(seconds: secondsToEnd))
} else {
callBack?(Func_HGT_secondsToTimeString(seconds: secondsToEnd))
}
}
/// 秒数转化为时间字符串
func Func_HGT_secondsToTimeString(seconds: Int) -> String {
//小时计算
let hours = seconds/3600
//分钟计算
let minutes = (seconds)%3600/60;
//秒计算
let second = (seconds)%60;
let timeString = String(format: "%02lu:%02lu:%02lu", hours, minutes, second)
return timeString
}
/// 秒数转化为时间字符串
func minToTimeString(seconds: Int) -> String {
//分钟计算
let minutes = seconds/60;
//秒计算
let second = (seconds)%60;
let timeString = String(format: "%02lu:%02lu", minutes, second)
return timeString
}
}
使用
import UIKit
import UIKit
class DemoView: UIView {
var loveTimer:XT_IntimateLoversTimer!
override func viewDidLoad() {
//seconds根据实际计算(活动结束时间减去当前时间得出的秒数)
if let applyEndTime = userModel?.apply?.applyEndTime {
// 当前时间
let timeInterval: TimeInterval = Date().timeIntervalSince1970
let timeStamp = Int(timeInterval)
let loveTime = (applyEndTime) / 1000 - timeStamp
loveTimer = XT_IntimateLoversTimer(seconds: loveTime, isMin: false, callBack: {[weak self] (text) in
let contentStr = String("\(text) 后结束")
self?.timeLabel.text = contentStr
})
}
}
}