Consider this macOS app code implemented with app delegate lifecycle:
App delegate:
SwiftUI:
What this does: correctly sets up the window and toolbar look. Toolbar has no buttons though.
What I would like to do: get the toolbar items added from SwiftUI added to the toolbar.
Everything works as expected when I have the window managed by the SwiftUI app lifecycle. However, I need to stick with the app delegate lifecycle for unrelated reasons.
Is this possible? How do I add toolbar buttons from SwiftUI to the toolbar of window that is created by app delegate?
App delegate:
Code Block swift func applicationDidFinishLaunching(_ aNotification: Notification) { let contentView = ContentView() window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 480, height: 300), styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], backing: .buffered, defer: false) window.toolbar = NSToolbar(identifier: "toolbar") window.title = "hello title" window.subtitle = "hello subtitle" window.isReleasedWhenClosed = false window.center() window.setFrameAutosaveName("Main Window") window.contentView = NSHostingView(rootView: contentView) window.makeKeyAndOrderFront(nil) }
SwiftUI:
Code Block struct ContentView: View { var body: some View { NavigationView { List { NavigationLink( destination: ItemView(), label: { Label("Something", systemImage: "folder.circle") }) NavigationLink( destination: ItemView(), label: { Label("Another", systemImage: "pencil.tip.crop.circle") }) }.listStyle(SidebarListStyle()) } .frame(maxWidth: .infinity, maxHeight: .infinity) .toolbar { ToolbarItem { Button(action: { print("Button clicked") }, label: { Label("Hello", systemImage: "pencil.circle") }) } } } } struct ItemView: View { var body: some View { Text("Hello, World!") .frame(maxWidth: .infinity, maxHeight: .infinity) .toolbar { ToolbarItem { Button(action: { print("Item button") }, label: { Label("Itemtool", systemImage: "lock.doc") }) } } } }
What this does: correctly sets up the window and toolbar look. Toolbar has no buttons though.
What I would like to do: get the toolbar items added from SwiftUI added to the toolbar.
Everything works as expected when I have the window managed by the SwiftUI app lifecycle. However, I need to stick with the app delegate lifecycle for unrelated reasons.
Is this possible? How do I add toolbar buttons from SwiftUI to the toolbar of window that is created by app delegate?