【问题标题】:SwiftUI Mac: Environment Object in secondary WindowSwiftUI Mac:辅助窗口中的环境对象
【发布时间】: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)
        }
    }
}

【问题讨论】:

    标签: swift macos swiftui


    【解决方案1】:

    直接申请SecondaryView,点赞

        @objc func openSecondaryWindow () {
            if self.secondaryWindow == nil {
                let secondaryView = SecondaryView()
                    .environmentObject(GlobalState.shared)      // << here !!
    
    

    【讨论】:

      猜你喜欢
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多