gpt4 book ai didi

macos - 如何在 SwiftUI、macOS 中打开另一个窗口?

转载 作者:行者123 更新时间:2023-12-03 17:23:14 24 4
gpt4 key购买 nike

我想在 macOS 上的 SwiftUI 应用程序中显示具有不同内容的第二个窗口。我找不到任何关于此的文档。下面的尝试不起作用。有谁知道怎么做?

class AppState: ObservableObject {
@Published var showSecondWindow: Bool = false
}

@main
struct MultipleWindowsApp: App {
@StateObject var appState = AppState()
var body: some Scene {
WindowGroup {
ContentView().environmentObject(appState)
}
WindowGroup {
if appState.showSecondWindow {
SecondContent()
}
}
}
}

struct ContentView: View {
@EnvironmentObject var appState: AppState
var body: some View {
VStack {
Text("Hello, world!")
Button("Open 2nd Window") {
appState.showSecondWindow = true
}
}.padding()
}
}

struct SecondContent: View {
var body: some View {
Text("Hello, from window #2.")
}
}

最佳答案

这是为 NSViewController 创建窗口的扩展程序,分配标题并打开它。

extension View {

@discardableResult
func openInWindow(title: String, sender: Any?) -> NSWindow {
let controller = NSHostingController(rootView: self)
let win = NSWindow(contentViewController: controller)
win.contentViewController = controller
win.title = title
win.makeKeyAndOrderFront(sender)
return win
}
}
用法:
Button("Open 2nd Window") {
SecondContent().openInWindow(title: "Win View", sender: self)
}

关于macos - 如何在 SwiftUI、macOS 中打开另一个窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64823492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com