简体   繁体   中英

SwiftUI EnvironmentObject out of sync with View

To give a simple example of what I'm doing I have an environment object:

class ViewModel: ObservableObject {
   @Published var x: CGFloat = 0
   @Published var y: CGFloat = 0
}

A view that's watching those numbers to adjust it's offset:

struct PrimaryView: View {
    @EnvironmentObject var model: ViewModel

// inside the view struct

    SomeView()
        .offset(x: model.x, y: model.y)
}

And another view that's responsible for changing those numbers:

struct ChangeView: View {
    @EnvironmentObject var model: ViewModel

// inside the view

    Button(action: {
               switch directionCondition {
                    case .up:
                        model.y += 10
                    case .down:
                        model.y -= 10
                    case .left:
                        model.x += 10
                    case .right:
                        model.x -= 10

           }) // end button here for brevity

When my app loads sometimes it works perfectly and other times the press will not fire initially at all then when you tap it again it will trigger.

Here's what I've tried so far. I put the mutations in the view model and only called the functions that caused the changes in the ChangeView . I dispatched those changes asynchronously using DispatchQueue . I removed the switch statement from the button and did those changes manually. And finally I put the mutations back in the view to see if that made a difference in the performance.

None of this worked so I'm starting to feel like this is potentially a bug on apple's part but I could also be doing something entirely incorrect. Also yes the environment object is correctly attached to the app root in App.Swift .

I switched from EnvironmentObject to ObservedObject and moved the subsequent code around to each view that I needed it in and now everything is working properly. My guess is that the Environment Object can get out of sync on initial load. As to why or how I'm not sure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM