Search code examples
swiftmacosswiftuimenubarextra

MenuBarExtra does not update it's view in the real time


I am trying to create a MenuBarExtra with dynamic content, but the content does not get updated

@main
struct MyApp: App {
    @State var text = ""

    var body: some Scene {
        WindowGroup {
            Text(text) // --------- 1
            TextField("", text: $text)
        }

        MenuBarExtra("A") {
            Text(text) // --------- 2
        }
        .menuBarExtraStyle(.window)
    }
}

In the code above, the Text[1] gets updated in the real time but the Text[2] does not update after the first appearance of MenuBarExtra


Solution

  • SwiftUI doesn't seem to correctly identify the dependencies of the menu bar extra. This might be a SwiftUI bug.

    You can work around this by passing a @Binding to a wrapper view.

    @State var text = ""
    
    var body: some Scene {
        WindowGroup {
            Text(text)
            TextField("", text: $text)
        }
    
        MenuBarExtra("A") {
            Wrapper(text: $text)
        }
        .menuBarExtraStyle(.window)
    }
    
    struct Wrapper: View {
        @Binding var text: String
        
        var body: some View {
            Text(text)
        }
    }
    

    This also works if you pass a ObservableObject to a @ObservedObject, or if you pass a @Observable instance.