struct ContentView: View {
var body: some View {
#if os(macOS)
VStack {
Button("Open Window 2") {
Window2().openInWindow(title: "Window 2", sender: self)
}
.contextMenu {
Button("window1menuItem") {
// Action for window1menuItem
}
}
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
}
#endif
}
}
struct Window2: View {
var body: some View {
Text("This is Window 2")
.frame(width: 300, height: 200)
.contextMenu {
Button("window2menuItem") {
// Action for window2menuItem
}
}
}
func openInWindow(title: String, sender: Any?) {
#if os(macOS)
let window = NSWindow(
contentRect: NSRect(x: 20, y: 20, width: 280, height: 200),
styleMask: [.titled, .closable, .miniaturizable, .resizable],
backing: .buffered, defer: false)
window.center()
window.setFrameAutosaveName(title)
window.contentView = NSHostingView(rootView: self)
window.makeKeyAndOrderFront(sender)
#endif
}
}
#Preview {
ContentView()
}
关闭window2时左上角有红点。 关闭 window1 不会使应用程序崩溃。在关闭 window1 后关闭 window2 确实会使应用程序崩溃,就像在打开 window1 的情况下关闭 window2 一样。
问题:
单独使用
openInWindow
,例如NSHostingView(rootView: Window2())
。
SwiftUI 也有
openWindow
Environment
属性。
在你的代码中
self
会立即被杀死。
https://www.hackingwithswift.com/quick-start/swiftui/how-to-open-a-new-window