How to achieve real-time SwiftUI Interface updates for variable changes in macOS Menu Bar?

135 views Asked by At

I have a SwiftUI application with a Menu Bar (MenuBarExtra), and it displays a counter that increments every second. I'm using an @Published variable in an ObservableObject to track changes in the counter, but the issue is that the interface doesn't update in real-time when the Menu Bar is open. The update only occurs when I open and close the Menu Bar again.

import SwiftUI

@main
struct _23App: App {
  @StateObject var viewModel = CounterViewModel()
  
  var body: some Scene {
    MenuBarExtra("Bar") {
      Button(String(self.viewModel.counter)) {
      }
    }
  }
}

class CounterViewModel: ObservableObject {
  @Published var counter: Int = 1
  
  init() {
    Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [self] _ in
      DispatchQueue.main.async {
        self.counter += 1
      }
    }
  }
}

Is there a way to make the interface update in real-time, even when the Menu Bar is open, without the need to close and reopen it?

0

There are 0 answers