【发布时间】:2021-03-29 16:36:19
【问题描述】:
我有一个使用 Xcode 12.4 的 Mac 应用开发人员
我发现了如何使用NSApp.sendAction(#selector(AppDelegate.openSecondaryWindow), to: nil, from: nil) 和以下代码设置和打开辅助窗口(有没有更好的方法?)。
问题是我想在SecondaryView 中访问ContentView 可以访问的同一个环境对象(global state)。如何做到这一点?
class AppDelegate: NSObject, NSApplicationDelegate {
var secondaryWindow: NSWindow!
func applicationDidFinishLaunching(_ notification: Notification) {
[...]
}
func applicationWillFinishLaunching(_ notification: Notification) {
NSWindow.allowsAutomaticWindowTabbing = false
}
func applicationShouldTerminateAfterLastWindowClosed(_ app: NSApplication) -> Bool {
return true
}
func applicationWillTerminate(_ notification: Notification) {
[...]
}
@objc func openSecondaryWindow () {
if self.secondaryWindow == nil {
let secondaryView = SecondaryView()
self.secondaryWindow = NSWindow(
contentRect: NSRect(x: 20, y: 20, width: 480, height: 300),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered,
defer: false)
self.spreadWindow.contentView = NSHostingView(rootView: secondaryView)
}
self.spreadWindow.makeKeyAndOrderFront(nil)
}
}
@main
struct MyApp: App {
@StateObject var globalState: GlobalState = GlobalState.shared
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(self.globalState)
}
}
}
【问题讨论】: