GCD定時(shí)器,以及數(shù)字轉(zhuǎn)換成時(shí)間格式類型的樣式的方法

//    MARK: 顯示時(shí)間label
private lazy var timeLabel: UILabel = {
    let label = UILabel()
    label.textColor = UIColor.white
    label.font = UIFont.systemFont(ofSize: 20)
    return label
}()

//    MARK: GCD定時(shí)器
var timerS: DispatchSourceTimer?
//設(shè)定定時(shí)時(shí)間
var countTime: Int = 0
func setTimerWithGCD()
{
    // 在global線程里創(chuàng)建一個(gè)時(shí)間源
    self.timerS = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
    // 設(shè)定這個(gè)時(shí)間源是每1.0秒循環(huán)一次,立即開始
    timerS?.scheduleRepeating(deadline: .now(), interval: DispatchTimeInterval.milliseconds(1000))
    // 設(shè)定時(shí)間源的觸發(fā)事件
    timerS?.setEventHandler(handler: {
        // 每1秒計(jì)時(shí)一次
        self.countTime += 1
        // 返回主線程處理一些事件,更新UI等等
        DispatchQueue.main.async {
            self.setTimerStr()
        }
    })
    //啟動(dòng)定時(shí)器
    timerS?.activate()
}

var minute: Int = 0
//    MARK: 將int轉(zhuǎn)換成時(shí)間格式樣式的方法
private func setTimerStr()
{
    if minute == 59 {minute = 0}
    
    if self.countTime > 59
    {
        self.countTime = 0
        minute += 1
    }
    self.timeLabel.text = "\(String.init(format: "%02d", minute)) " + ": " + "\(String.init(format: "%02d", self.countTime))"
    
}
image.png

上面的是正序的時(shí)間,下面這個(gè)是倒敘的時(shí)間

//    MARK: GCD定時(shí)器
var timerS: DispatchSourceTimer?
//設(shè)定定時(shí)時(shí)間
var countTime: Int = 60
func setTimerWithGCD()
{
    // 在global線程里創(chuàng)建一個(gè)時(shí)間源
    self.timerS = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
    // 設(shè)定這個(gè)時(shí)間源是每1.0秒循環(huán)一次,立即開始
    timerS?.scheduleRepeating(deadline: .now(), interval: DispatchTimeInterval.milliseconds(1000))
    // 設(shè)定時(shí)間源的觸發(fā)事件
    timerS?.setEventHandler(handler: {
        // 每1秒計(jì)時(shí)一次
        self.countTime -= 1
        // 返回主線程處理一些事件,更新UI等等
        DispatchQueue.main.async {
            self.setTimerStr()
        }
    })

    //啟動(dòng)定時(shí)器
    if #available(iOS 10.0, *) {
        timerS?.activate()
    } else {
        timerS?.resume()
    }
}

//表示倒計(jì)時(shí)總時(shí)間
var minute: Int = 14
//    MARK: 將int轉(zhuǎn)換成時(shí)間格式樣式的方法
private func setTimerStr()
{
    if minute <= 0 && countTime <= 0
    {
        print("時(shí)間結(jié)束")
        self.timeLabel.text = "00: 00"
        timerS?.cancel()
        // 這里進(jìn)行發(fā)服務(wù),時(shí)間變成00之后需要做的事情
        return
    }

    if self.countTime < 0
    {
        self.countTime = 59
        minute -= 1
    }
    self.timeLabel.text = "\(String.init(format: "%02d", minute)) " + ": " + "\(String.init(format: "%02d", self.countTime))"
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容