話不多說(shuō),直接上代碼硬鞍!~
定時(shí)器
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() {
//如果崩在這里慧瘤,說(shuō)明你沒(méi)有在使用Timer的VC里面的deinit方法里調(diào)用invalidate()方法
_ = _aTarget.perform(_aSelector)
}
deinit {
print("計(jì)時(shí)器已銷毀")
}
}
需要調(diào)用的類封裝
import UIKit
class XT_IntimateLoversTimer {
/// 活動(dòng)結(jié)束秒數(shù)
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)
//如果希望對(duì)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))
}
}
/// 秒數(shù)轉(zhuǎn)化為時(shí)間字符串
func Func_HGT_secondsToTimeString(seconds: Int) -> String {
//小時(shí)計(jì)算
let hours = seconds/3600
//分鐘計(jì)算
let minutes = (seconds)%3600/60;
//秒計(jì)算
let second = (seconds)%60;
let timeString = String(format: "%02lu:%02lu:%02lu", hours, minutes, second)
return timeString
}
/// 秒數(shù)轉(zhuǎn)化為時(shí)間字符串
func minToTimeString(seconds: Int) -> String {
//分鐘計(jì)算
let minutes = seconds/60;
//秒計(jì)算
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根據(jù)實(shí)際計(jì)算(活動(dòng)結(jié)束時(shí)間減去當(dāng)前時(shí)間得出的秒數(shù))
if let applyEndTime = userModel?.apply?.applyEndTime {
// 當(dāng)前時(shí)間
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) 后結(jié)束")
self?.timeLabel.text = contentStr
})
}
}
}