PTTimer - 可自定义的 Swift 定时器类
PTTimer 是一个Swift类,可用于创建精确跟踪时间的计时器。
PTTimer 是我为一个我一直在制作的 iOS 应用程序而创建的项目。我决定将其从我的应用中提取出来并开源,因为我注意到并没有太多优质资源可供 Swift 秒表/倒计时计时器。
背景
我看到一些博客文章建议使用一个简单的计数器来构建定时器。这意味着要做以下事情
绝对不要这么做!!
let seconds = 60
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self,
selector: #selector(timerRunning),
userInfo: nil, repeats: true)
func timerRunning() {
second -= 1
}
这绝对是一个 非常糟糕 的主意(正如我从艰难的经验中学到的),因为 Swift 的 Timer
在应用处于后台时不会触发。因此,当您从后台返回并且 Timer
再次触发时,它会从上次离开的地方开始。如果应用在后台持续了 30 秒,您的计时器根本不会为此做任何更正。这将确保您得到一个不准确的计时器。那还有什么意义呢??
PTTimer 在下面使用 Timer
,但 PTTimer
的优势在于它为您管理计时器时钟。我发现处理应用后台的最佳方式是使用系统时钟来管理计时器,这使得即使在下一个 Timer
触发时也可以进行自我纠正。
特点
- 无依赖!
- 附带两个内置计时器
- 一个 CountUp 计时器(从 0 开始计数)
- 一个 CountDown 计时器(从您指定的秒数开始倒计时到 0)
- 即使在您的应用处于后台时也继续计时
- 基于设备时钟精确计数时间
- 可以继承:重写
PTTimer
上的方法来完全自定义您的计时器。
安装
PTTimer 通过 CocoaPods 提供。要安装,只需在 Podfile 中添加以下行
pod 'PTTimer'
使用方式
首先,请确保导入 import PTTimer
0
。
创建一个从初始秒数计时的定时器,时间倒计时到 // This creates a countdown timer that begins at 5 minutes
let timer = PTTimer.Down(initialTime: 60 * 5)
0
开始上计数达到最大秒数的定时器
创建一个从 - (默认
90*60
或者 90 分钟)
let timer = PTTimer.Up()
// customize the maxSeconds
let timer = PTTimer.Up(maxSeconds: 60 * 15)
与计时器交互
// start the timer
timer.start()
// pause the timers
timer.pause()
// reset the timer back to the original state
// (0 if count up, initialTime if count down)
timer.reset()
// read the state of the timer (.paused, .running, .reset)
let state = timer.state
// read the current seconds of the timer
let currentSeconds = timer.seconds()
您可以自由地通过从 PTTimer
继承来创建自己的计时器
代理函数
利用代理在定时器状态改变和定时器时间改变时采取行动
func timerTimeDidChange(seconds: Int) {
// Update labels, buttons when the timer seconds have changed
// consider a formatter to turn seconds into 00:00 or similar
}
func timerDidPause() {
// update label colors, buttons for a paused timer
}
func timerDidStart() {
// update label colors, buttons for a started timer
}
func timerDidReset() {
// update label colors, buttons now that the timer has been reset
}
示例应用程序
查看 ExampleTimer
应用程序以了解 PTTimer
的示例用法
从 ExampleTimer
目录运行 pod install
。
在 XCode 中打开 ExampleTimer/ExampleTimer.xcworkspace
并运行。
您可以在 ExampleTimer/ExampleTimer/ViewController.swift
中查看计时器的 UI 代码
贡献
欢迎并鼓励贡献!如果您认为任何内容都可以使此项目变得更好,我非常乐意听取您的意见。我保留根据自己的意愿接受或拒绝更改的权利。
- 分支它
- 创建您的功能分支 (
git checkout -b my-new-feature
) - 提交您的更改 (
git commit -am 'Add some feature'
) - 将更改推送到分支 (
git push origin my-new-feature
) - 创建拉取请求
其他信息
通过 PTTimer 的 GitHub Issues 报告错误,讨论功能和一般反馈。在提交任何新问题之前,请务必查看我们的 历史问题。
如果您正在提交有关应用程序崩溃的问题,堆栈跟踪很有帮助,但还需要额外的上下文,即代码和说明,以便有用。
许可证
PTTimer 可在 MIT 许可证下使用。有关更多信息,请参阅 LICENSE 文件。