0

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()
                }
        })
    }
}
  • define your observableObject like this in TestB @ObservedObject var object= ObservableTest() – Ali Momeni Apr 29 '21 at 10:33
  • The purpose is to use EnvironmentObject to pass values across hierarchies – 王小叨 Apr 29 '21 at 10:38
  • try making the class and var public – Ali Momeni Apr 29 '21 at 11:23
  • Add this `@EnvironmentObject var object: ObservableTest` to `TestA` and then init `TextB` like this `TestB().environmentObject(object)` you have to pass it along each `View` – lorem ipsum Apr 29 '21 at 11:38
  • @AliMomeni that is not how you `init` an `@ObservableObject` it should come from a `ParentView` only `@StateObject` should be init like that. See [Apple Documentation](https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app) – lorem ipsum Apr 29 '21 at 11:40
  • you are right @loremipsum. – Ali Momeni Apr 29 '21 at 12:33
  • Follow the official documentation to do, drop down and click on the page again, still reported that the object could not be found – 王小叨 Apr 30 '21 at 05:17

0 Answers0