MacOS(Sonoma)上的 SwiftUI 中的超级简单应用程序崩溃引起的问题

问题描述 投票:0回答:1
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()
}

像这样崩溃 CrashSite

关闭window2时左上角有红点。 关闭 window1 不会使应用程序崩溃。在关闭 window1 后关闭 window2 确实会使应用程序崩溃,就像在打开 window1 的情况下关闭 window2 一样。

问题:

  1. 我的示例应用程序有什么明显的问题吗
  2. 针对 MacOS 和 iPadOS 的生产级应用程序是否最好避免使用 SwiftUI? 谢谢。索诺玛 14.4.1 Xcode 15.3
macos swiftui macos-sonoma
1个回答
0
投票

单独使用

openInWindow
,例如
NSHostingView(rootView: Window2())

SwiftUI 也有

openWindow
Environment
属性。

在你的代码中

self
会立即被杀死。

https://www.hackingwithswift.com/quick-start/swiftui/how-to-open-a-new-window

© www.soinside.com 2019 - 2024. All rights reserved.