我有一个使用 Xcode 12.4 的 Mac 应用程序开发人员。
我已经找到了如何使用
NSApp.sendAction(#selector(AppDelegate.openSecondaryWindow), to: nil, from: nil)
设置和打开辅助窗口。 (有更好的办法吗?)
问题是我想在
SecondaryView
中访问 globalState
可以访问的相同环境对象 ContentView
。如何做到这一点?
我的代码:
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)
}
}
}
直接应用到
SecondaryView
,就像
@objc func openSecondaryWindow () {
if self.secondaryWindow == nil {
let secondaryView = SecondaryView()
.environmentObject(GlobalState.shared) // << here !!