直接看主要代码
let endDate = datePicker.date
let startDate = Date()
let timeInterval:TimeInterval = endDate.timeIntervalSince(startDate)
if timer == nil {
var timeout = timeInterval
if timeout != 0 {
let queue = DispatchQueue.global()
timer = DispatchSource.makeTimerSource(flags: [],queue: queue)
timer?.scheduleRepeating(wallDeadline: DispatchWallTime.now(),interval: .seconds(1))
timer?.setEventHandler(handler: {
if timeout <= 0 {
self.timer?.cancel()
self.timer = nil
DispatchQueue.main.async(execute: {
self.day.text = "00"
self.hour.text = "00"
self.minute.text = "00"
self.second.text = "00"
})
} else {
let days = Int(timeout) / (3600 * 24)
if days == 0 {
self.day.text = ""
}
let hours = (Int(timeout) - Int(days) * 24 * 3600) / 3600
let minutes = (Int(timeout) - Int(days) * 24 * 3600 - Int(hours) * 3600) / 60
let seconds = Int(timeout) - Int(days) * 24 * 3600 - Int(hours) * 3600 - Int(minutes) * 60
DispatchQueue.main.async(execute: {
if days == 0 {
self.day.text = "0"
} else {
self.day.text = "\(days)"
}
if hours < 10 {
self.hour.text = "0" + "\(hours)"
} else {
self.hour.text = "\(hours)"
}
if minutes < 10 {
self.minute.text = "0" + "\(minutes)"
} else {
self.minute.text = "\(minutes)"
}
if seconds < 10 {
self.second.text = "0" + "\(seconds)"
} else {
self.second.text = "\(seconds)"
}
})
timeout -= 1
}
})
timer?.resume()
}
}
DEMO效果图
原文链接:https://www.f2er.com/swift/322116.html