我成功地将environmentObject appSettings传递到我的视图中。我可以用它来修改我的字体和视图中的选择器。但是,如果我尝试在视图 init() 中访问环境对象发布的变量,它会崩溃:
Thread 1: Fatal error: No ObservableObject of type AppSettings found.
A View.environmentObject(_:) for AppSettings may be missing as an ancestor of this view.
在自定义 SwiftUI View 初始值设定项中使用environmentObject 是否有特殊规则?
这是我的视图代码的开始。环境对象是appSettings。如果我在初始化程序中注释掉第 2 行并取消注释第 3 行,则应用程序可以正常工作。请注意,我稍后在选取器中成功使用了“appSettings.interfaces”。
struct CaptureFilterView: View {
@State var etherCapture: EtherCapture? = nil
@EnvironmentObject var appSettings: AppSettings
@Binding var frames: [Frame]
@State var captureFilter: String = ""
@State var error: String = ""
@State var numberPackets = 10
@State var interface: String = ""
init(frames: Binding<[Frame]>) {
self._frames = frames
self.interface = appSettings.interfaces.first ?? "en0" //CRASH HERE
//self.interface = "en0" //uncomment this and comment line above to make app "work"
}
var body: some View {
HStack() {
...
Picker(selection: $interface, label: Text("")) {
ForEach(appSettings.interfaces, id: \.self) { interfaceName in
Text(interfaceName).tag(interfaceName)
}
}
这是我在 AppDelegate.swift 中创建顶级内容视图的位置
let contentView = ContentView(showCapture: true).environmentObject(appSettings)
And 只是要确定在顶级 ContentView 中创建 CaptureFilterView 时,我还会传递environmentObject。这是不必要的,也不会改变行为。
if showCapture { CaptureFilterView(frames: self.$frames).environmentObject(appSettings) }
作为参考,这里是我的 appSettings 的顶部:
class AppSettings: ObservableObject {
@Published var font: Font
@Published var interfaces: [String]