SwiftUI No ObservableObject of type ObservableTest found. A View.environmentObject(_:) for ObservableTest may be missing as an ancestor of this view

82 views Asked by At

To reproduce the problem, please use the following code and do the following Operation steps:

  1. click TestB View twice,
  2. scroll down to close the page, and the above problem will occur in the process.
import SwiftUI

@main
struct SwiftUIStudyApp: App {
    @State private var isShow: Bool = false
    var body: some Scene {
        WindowGroup {
            TestA().environmentObject(ObservableTest())
        }
    }
}


class ObservableTest: ObservableObject {
    @Published var test: Bool = false
}

struct TestA: View {
    @State var show: Bool = false
    var body: some View {
        VStack(alignment: .center, spacing: 0, content: {
            Spacer()
            Text("next")
                .onTapGesture {
                    show.toggle()
                }
            Spacer()
        })
        .sheet(isPresented: $show, content: {
            TestB()
        })
    }
}
struct TestB: View {
    
    @EnvironmentObject var object: ObservableTest

    var body: some View {
        VStack(alignment: .center, spacing: 0, content: {
            RoundedRectangle(cornerRadius: 25.0)
                .fill(object.test == true ? Color.red : Color.green)
                .onTapGesture {
                    object.test.toggle()
                }
        })
    }
}
0

There are 0 answers