我有两个视图。主视图和中断视图。我有一个计时器在主视图中运行,它会倒计时到零。当计时器达到零时,我希望能够将屏幕切换到中断视图。我使用MVVM跟踪计时器。使用.onReceive使计时器看起来像是在后台运行。
我试着用布尔值来检查计时器是否已经达到零,并基于此更改视图,但它不起作用,并给出一个错误,说视图的结果没有在任何地方使用。如果有任何帮助,我在内容视图中有一个导航视图。
先谢谢你。
代码片段:
主视图:
struct MainView: View {
var body: some View {
VStack(alignment: .center, spacing: 50, content: {
Button(action: {
if !fbManager.isTimerStarted {
fbManager.start()
fbManager.isTimerStarted = true
}
else {
fbManager.pause()
fbManager.isTimerStarted = false
}
}, label: {
Image(systemName: fbManager.isTimerStarted == true ? "pause.fill" : "play.fill")
.resizable()
.scaledToFit()
.frame(width: 50, height: 50)
.foregroundColor(Color(red: 1.00, green: 1.00, blue: 1.00))
})
.onReceive(NotificationCenter.default.publisher(
for: UIScene.didEnterBackgroundNotification)) { _ in
if fbManager.isTimerStarted {
movingToBackground()
}
}
.onReceive(NotificationCenter.default.publisher(
for: UIScene.willEnterForegroundNotification)) { _ in
if fbManager.isTimerStarted {
movingToForeground()
}
}
})
}
}
func movingToBackground() {
print("Moving to the background")
notificationDate = Date()
fbManager.pause()
}
func movingToForeground() {
print("Moving to the foreground")
let deltaTime: Int = Int(Date().timeIntervalSince(notificationDate))
fbManager.secondsElapsed -= deltaTime
fbManager.start()
}
}
查看型号:
class FocusBreakManager: ObservableObject {
var timer: Timer = Timer()
func start() {
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [self] _ in
self.secondsElapsed -= 1
self.focusfill += 0.01667
focusTime = String(secondsElapsed)
focusTime = formatCounter()
if secondsElapsed <= 0 {
stop()
}
}
}
func formatCounter() -> String {
let minutes = Int(secondsElapsed) / 60 % 60
let seconds = Int(secondsElapsed) % 60
return String(format : "%02i : %02i", minutes, seconds)
}
}
1条答案
按热度按时间68bkxrlz1#
嘿,为了跟上你的解决方案,这里有一个如何工作的例子,你需要使用
@ObservedObject
属性 Package 器,以便从你的视图监视更新。你也可以看看autoconnect api这里有一个很棒的教程:https://www.hackingwithswift.com/books/ios-swiftui/triggering-events-repeatedly-using-a-timer