I am trying to create a progress bar which updates based on two values received via bluetooth (should represent a race like thing, so based on which value is higher, the progress bar grows or shrinks). For updating the view I followed this tutorial: https://dippnerd.com/swiftui-timer-ui-refresh, but for me it is not working. The timer works just fine, but my view does not update. In my root view I do not use the TimerWrapper, I only use it in a secondary view, so I do not have the @EnvironmentObject of TimerWrapper in my root view controller.
TimerWrapper:
import SwiftUI
import Combine
class TimerWrapper : ObservableObject {
let willChange = PassthroughSubject<TimerWrapper, Never>()
var timer : Timer!
func start(withTimeInterval interval: Double) {
self.timer?.invalidate()
self.timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { _ in
print("timer fired")
self.willChange.send(self)
}
}
}
The progressBar view looks as following:
import SwiftUI
struct MultiplayerBar: View {
@EnvironmentObject var timerWrapper: TimerWrapper
var body: some View {
GeometryReader { geometryReader in
Rectangle()
.fill(Color.green)
Rectangle()
.fill(Color.red)
.frame(width: getPlayer1Progress(maxWidth: geometryReader.size.width))
.animation(.easeIn)
}
.frame(height: 200)
.cornerRadius(15)
.padding()
}
}
struct MultiplayerBar_Previews: PreviewProvider {
static var previews: some View {
MultiplayerBar()
.environmentObject(TimerWrapper())
}
}
And it is called like this:
MultiplayerBar()
.shadow(radius: 5)
.environmentObject(TimerWrapper())
The timer is started in the SceneDelegate.swift file:
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
let timer = TimerWrapper()
timer.start(withTimeInterval: 1)
window.rootViewController = UIHostingController(rootView: ShowTrainingView()
.environmentObject(BLEControl.BLESingleton)
.environmentObject(UserData()))
self.window = window
window.makeKeyAndVisible()
}
Actually I am not quite sure if my approach is right and how I could fix it. Thanks for any help in advance.