Swiftui - 定时器在一段时间内漂移
Swiftui - Timer drifting over a period of time
我有一个锻炼计时器,可以让用户锻炼 30 秒,然后休息 10 秒。我有一些视觉方面可以用一些文字来表示这是休息时间还是锻炼时间。当计时器第一次启动时它工作正常,但随着时间的推移它会逐渐消失并且文本开始提前更改,然后它应该。一旦完成,我就会使我的计时器失效,我不明白为什么我会因为时间已经过去而得到不同的结果。
func start() {
centreText = "Workout"
Timer.scheduledTimer(withTimeInterval: 30, repeats: false) { timer in
timer.invalidate()
break()
}
}
func break() {
breatheText = "Break"
Timer.scheduledTimer(withTimeInterval: 10, repeats: false) { timer in
timer.invalidate()
start()
}
}
我如何调用开始:
.onAppear {
withAnimation(.workout(workDuration: 30, break: 10), {
start()
})
锻炼动画:
public static func workout(workDuration: Double, break: Double) -> Animation {
return Animation.easeInOut(duration: workDuration).delay(break).repeatForever(autoreverses: true)
}
由于 SwiftUI 中的视图是 struct
,因此最好使用配置器 class
使用 ObservableObject
来更新 UI。处理此 class 中的所有计时器并使用视图分配给的 Published
变量。
struct MyView: View {
@StateObject private var config = MyViewConfig()
var body: some View {
Text(config.message)
Button("Start", action: config.start)
}
}
private final class MyViewConfig: ObservableObject {
@Published private(set) var message = "Workout"
func start() {
// star timer and update message
message = "Workout"
}
func stop() {
// stop timer and update message
message = "Break"
}
}
我有一个锻炼计时器,可以让用户锻炼 30 秒,然后休息 10 秒。我有一些视觉方面可以用一些文字来表示这是休息时间还是锻炼时间。当计时器第一次启动时它工作正常,但随着时间的推移它会逐渐消失并且文本开始提前更改,然后它应该。一旦完成,我就会使我的计时器失效,我不明白为什么我会因为时间已经过去而得到不同的结果。
func start() {
centreText = "Workout"
Timer.scheduledTimer(withTimeInterval: 30, repeats: false) { timer in
timer.invalidate()
break()
}
}
func break() {
breatheText = "Break"
Timer.scheduledTimer(withTimeInterval: 10, repeats: false) { timer in
timer.invalidate()
start()
}
}
我如何调用开始:
.onAppear {
withAnimation(.workout(workDuration: 30, break: 10), {
start()
})
锻炼动画:
public static func workout(workDuration: Double, break: Double) -> Animation {
return Animation.easeInOut(duration: workDuration).delay(break).repeatForever(autoreverses: true)
}
由于 SwiftUI 中的视图是 struct
,因此最好使用配置器 class
使用 ObservableObject
来更新 UI。处理此 class 中的所有计时器并使用视图分配给的 Published
变量。
struct MyView: View {
@StateObject private var config = MyViewConfig()
var body: some View {
Text(config.message)
Button("Start", action: config.start)
}
}
private final class MyViewConfig: ObservableObject {
@Published private(set) var message = "Workout"
func start() {
// star timer and update message
message = "Workout"
}
func stop() {
// stop timer and update message
message = "Break"
}
}