我使用 SwiftUI 创建了一个应用程序,当我尝试显示一个按钮时,会出现以下错误消息:
Thread 1: Fatal error: No ObservableObject of type ModelData found. A View.environmentObject(_:) for ModelData may be missing as an ancestor of this view.
当我尝试@EnvironmentObject
显示我的应用程序的一个视图时尝试使用时会发生这种情况。
我的代码是
struct OpportunityDetail: View {
@EnvironmentObject var modelData: ModelData
var opportunity: Opportunity
var opportunityIndex: Int {
modelData.opportunities.firstIndex(where: { $0.id == opportunity.id })!
}
var body: some View {
ScrollView {
MapView(coordinate: opportunity.locationCoordinate)
.frame(height: 300)
.ignoresSafeArea(edges: .top)
CircleImage(opportunity: opportunity)
.offset(y: -130)
.padding(.bottom, -130)
VStack {
VStack(alignment: .leading) {
Text(opportunity.position)
.font(.title)
HStack {
Text(opportunity.name)
.font(.subheadline)
Spacer()
Text(opportunity.city)
.font(.subheadline)
}
.font(.subheadline)
.foregroundColor(.secondary)
Divider()
Text("About the Opportunity")
.font(.title2)
Text(opportunity.description)
ApplyButton(isSet: $modelData.opportunities[opportunityIndex].isApplied)
}
.padding()
}
}
.navigationTitle(opportunity.name)
.navigationBarTitleDisplayMode(.inline)
}
}
但是,视图的预览和实时预览工作正常
struct OpportunityDetail_Previews: PreviewProvider {
static let modelData = ModelData()
static var previews: some View {
OpportunityDetail(opportunity: modelData.opportunities[0])
.environmentObject(modelData)
}
}
我知道我必须在某个地方传递我的环境对象,但不知道如何。我将不胜感激任何人的帮助。