【问题标题】:How to confirm ObservableObject for an AppDelegate?如何确认 AppDelegate 的 ObservableObject?
【发布时间】:2020-07-20 15:23:24
【问题描述】:

我正在尝试观察 macOS AppDelegate 中的值,但出现错误

ContentView.swift:14:6:通用结构“ObservedObject”需要“NSApplicationDelegate?”符合'ObservableObject'

当我尝试使用as! ObservedObject 将对象转换为ObservedObject 时,我遇到了另一个错误

ContentView.swift:14:6:通用结构“ObservedObject”要求“ObservedObject”符合“ObservableObject”

AppDelegate.swift 文件内

import Cocoa
import SwiftUI
import Combine

@NSApplicationMain
class AppDelegate: NSObject, ObservableObject, NSApplicationDelegate  {
    var isFocused = true
    
    // Other code app life-cycle functions
}

ContentView.swift 文件内

import SwiftUI
import Combine

struct ContentView: View {
    @ObservedObject var appDelegate = NSApplication.shared.delegate
    
    // Other UI code
}

【问题讨论】:

    标签: macos swiftui combine


    【解决方案1】:

    这看起来像是概念的混合......我建议避免这样......而是创建显式可观察类。

    如下图(略)

    class AppState: ObservableObject {
      @Published var isFocused = true
    }
    
    @NSApplicationMain
    class AppDelegate: NSObject, NSApplicationDelegate  {
        var appState = AppState()
        
        // Other code app life-cycle functions
    
         // in place where ContentView is created
         ...
         ContentView().environmentObject(self.appState)
         ...
    }
    

    在 ContentView 中使用它

    struct ContentView: View {
        @EnvironmentObject var appState: AppState
        
        // Other UI code
    
        var body: some View {
           // .. use self.appState.isFocused where needed
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-10
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-20
      • 2023-03-18
      • 1970-01-01
      相关资源
      最近更新 更多