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.
}
}