7

I have the following view in my macOS app:

struct ViewWithToolbar: View {
    var body: some View {
        Group {
            Text("Hello from ViewWithToolbar!")
                .padding()
        }
        .toolbar {
            Button("Action1") {  }
            Button("Action2") {  }
        }
        .frame(minWidth: 500, minHeight: 400.0)
    }
}

If I pass this view in the App declaration, everything works as expected. The problem begins when I tried to present this view in a new window, like in the following example:

struct RootView: View {
    var body: some View {
        Group {
            Button("Present View with Toolbar") {
                let controller = NSHostingController(rootView: ViewWithToolbar())
                let window = NSWindow(contentViewController: controller)
                window.contentViewController = controller
                window.title = "View with Toolbar"
                window.styleMask = [.titled, .closable, .miniaturizable, .resizable]
                window.makeKeyAndOrderFront(nil)
            }
            .padding()
        }
        .frame(minWidth: 500, minHeight: 400)
    }
}

The view does open in a new window, however the toolbar is not showing anymore. It seems to ignore the top bar altogether, apart from the title I pass in to the window.

What could be causing this issue? Does it have to do with the way I'm presenting the window? Is there a more SwiftUI'ish way of presenting a new window that can solve this?

Eilon
  • 2,698
  • 3
  • 16
  • 32
  • `window.toggleToolbarShown()` ? – Moose Dec 24 '21 at 11:50
  • 1
    Have the same issue, can confirm `window?.toggleToolbarShown(nil)` does not work. – Sabesh Bharathi Feb 23 '22 at 12:09
  • I would agree window.toggleToolbarShown() does not work. – iphaaw May 23 '22 at 07:36
  • @iphaaw It does not work that way. NSWindow and NSToolbar are different things and constructed separately, in default flow it is internal responsibility of `WindowGroup`(they have internal AppWindowController for that), but if you create NSWindow manually then you have to create NSToolbar manually as well (a lot of code, delegate, etc. definitely helper controller is needed). IMO just create another WindowGroup if it is needed separated and activate it by universal links, etc, like in https://stackoverflow.com/a/67363964/12299030 – Asperi May 23 '22 at 12:06
  • 3
    I think you are fighting SwiftUI and making it harder than it needs to be. Look at the answer that starts with [Tested on Xcode 13 beta, SwiftUI 3.0](https://stackoverflow.com/questions/64823492/how-to-open-another-window-in-swiftui-macos). It shows you the SwiftUI way of opening windows. – lorem ipsum May 30 '22 at 11:33

0 Answers0