【发布时间】:2020-12-18 00:38:18
【问题描述】:
考虑使用应用委托生命周期实现的这个 macOS 应用代码:
应用委托:
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:
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")
})
}
}
}
}
它的作用:正确设置窗口和工具栏的外观。工具栏虽然没有按钮。它看起来像这样:
我想做的事:将 SwiftUI 添加的工具栏项添加到工具栏中。
当我拥有由 SwiftUI 应用程序生命周期管理的窗口时,一切都按预期工作。但是,出于不相关的原因,我需要坚持应用程序委托的生命周期。
这可能吗?如何将 SwiftUI 中的工具栏按钮添加到应用委托创建的窗口的工具栏?
【问题讨论】: