How to update menu bar extras based on view model?

Viewed 130

I have a Swift UI app for macOS, and it is an app that lives in the menu bar (menu bar extras). It periodically pulls data (part of which contains an array of objects) into a view model (ObservableObject) - and the length of the array changes.

I am trying to render a Swift UI view inside NSHostingView so that my menu bar app updates accordingly as the view model changes. However, as the length of the data varies, the height of the Swift UI view also changes based on data updates. In order to render the Swift UI view in NSHostingView, I need to set the frame of the NSHostingView as an NSRect with a fixed width and length.

My problem is: how can I update the height of my NSHostingView's frame (defined in AppDelegate) when the data updates?

What I am doing now is applying a fixed height to the NSRect, something like so:

// AppDelegate.swift

func applicationDidFinishLaunching(_ notification: Notification) {
    // ...
    let menuItem = NSMenuItem()
    let hostingView = NSHostingView(rootView: MenuExtrasView())
    hostingView.frame = NSRect(x: 0, y: 0, width: 280, height: 400)
    menuItem.view = hostingView
    menu.addItem(menuItem)
    // ...
}

... where my MenuExtrasView() is the Swift UI view that should be of varying height.

0 Answers
Related