目前正在创建一个 SwiftUI 应用程序,我在尝试解决 ObservedObject 和选择器的问题时遇到了困难。我的内容视图:
struct ContentView: View {
@ObservedObject var timerManager = TimerManager()
...
var body: some View{
Circle()
.onTapGesture(perform: {
self.timerManager.setTimerLength(seconds: self.settings.selectedSecondPickerIndex, minutes: self.settings.selectedMinutePickerIndex)
self.timerManager.start()
})
Picker(selection: self.$settings.selectedSecondPickerIndex, label: Text("")) {
ForEach(0 ..< 60) {
Text("\(secondsToString(seconds: self.availableTimeInterval[$0]))")
}
}
}
...
}
TimerManager 管理一个计时器。班上:
class TimerManager: ObservableObject {
@Published var secondsLeft : Int = -1
var secondsTotal : Int = -1
var timer = Timer()
func start() {
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { timer in
if secondsLeft == 0 {
self.secondsLeft = secondsTotal
timer.invalidate()
}
else{
self.secondsLeft -= 1
}
}
RunLoop.current.add(timer, forMode: RunLoop.Mode.common)
}
func setTimerLength(seconds: Int, minutes: Int) {
let totalSeconds: Int = seconds + minutes * 60
secondsTotal = totalSeconds
secondsLeft = totalSeconds
}
...
}
我需要从 ContentView 访问计时器类的 secondsLeft 变量以显示剩余时间。当计时器运行时,secondsLeft 变量会每秒更新一次,并且 ContentView 会重新呈现。问题是,当计时器运行时,我不能“轻弹”我的选择器,它总是重置,这里也指出:https ://forums.developer.apple.com/thread/127218 。但与那篇文章不同的是,选择器的“选择”变量对问题没有任何影响。如果我从 secondsLeft 变量中删除 @Public,一切正常(问题是我无法显示剩余时间)。
有人知道如何解决这个问题吗?
谢谢回答!