1.需求.在view上展示一個label,用來顯示當前時間并走秒
2.思路.有兩個方法,一個是用Timer,創建一個定時器,用Date獲取當前時間,代碼如下
第一個方法:
在viewcontroller中定義變量
private var timer : Timer?
private var timeLb : UILabel?
在viewdidload中創建timeLb并加入view,創建Date對象
timeLb = UILabel.init(frame: CGRect(x: (kScreenWidth - 10) * 0.5 + 10, y: kScreenHeight * 0.5, width: (kScreenWidth - 10) * 0.5, height: 20))
timeLb?.text = "09:09:45"
timeLb?.textColor = RGBCOLOR(r: 66, 176, 216)
timeLb?.textAlignment = NSTextAlignment.left
view.addSubview(timeLb!)
let currentDate = Date(timeIntervalSinceNow: 1)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
timeLb?.text = dateFormatter.string(from: currentDate)
addCycleTimer()
// 添加定時器
fileprivate func addCycleTimer() {
timer = Timer(timeInterval: 1.0, target: self, selector: #selector(self.handleTimer), userInfo: nil, repeats: true)
RunLoop.main.add(timer!, forMode:RunLoopMode.commonModes)
}
@objc private func handleTimer (){
let currentDate = Date(timeIntervalSinceNow: 1)
// let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
timeLb?.text = dateFormatter.string(from: currentDate)
第二個方法是用DispatchSourceTimer在子線程實現,代碼如下
//
// ViewController.swift
import UIKit
class ViewController: UIViewController {
private var timeLb : UILabel?
var codeTimer: DispatchSourceTimer?
override func viewDidLoad() {
super.viewDidLoad()
timeLb = UILabel.init(frame: CGRect(x: (UIScreen.main.bounds.size.width - 10) * 0.5 + 10, y: UIScreen.main.bounds.size.height * 0.5, width: (UIScreen.main.bounds.size.width - 10) * 0.5, height: 20))
timeLb?.text = ""
timeLb?.textAlignment = NSTextAlignment.left
view.addSubview(timeLb!)
// 定義需要計時的時間
var timeCount = 60
// 在global線程里創建一個時間源
codeTimer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
// 設定這個時間源是每秒循環一次,立即開始
codeTimer?.scheduleRepeating(deadline: .now(), interval: .seconds(1))
// 設定時間源的觸發事件
codeTimer?.setEventHandler(handler: {
// 每秒計時一次
timeCount = timeCount - 1
let currentDate = Date(timeIntervalSinceNow: 1)
// let currentDate = Date()
// let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
// 返回主線程處理一些事件,更新UI等等
DispatchQueue.main.async {
self.timeLb?.text = dateFormatter.string(from: currentDate)
}
})
// 啟動時間源
codeTimer?.resume()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
codeTimer?.cancel()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}