简体   繁体   中英

SwiftUI - EnvironmentObject Published var to NavigationLink's Selection?

I have a class I use as EnvironmentObject with a screen variable I want to use to control what screen the user is in. I use network calls to change this value, expiration seconds to move to another view, so I need my NavigationView to move to the adequate screen when this value changes.

For the class I have something like this:

class MyClass: NSObject, ObservableObject {
  @Published var screen: String? = "main"
}

And for the main view I have something like this:

struct ContentView: View {

   @EnvironmentObject var myClass: MyClass

   var body: some View {
      ZStack {
         NavigationView() {
            NavigationLink(destination: MainView(), tag: "main", selection: self.$myClass.screen) 
            { 
               EmptyView()
            }
         }
      }
    }
}

I don't seem to be able to work this way.

As a workaround I have done:


struct ContentView: View {

   @EnvironmentObject var myClass: MyClass

   var body: some View {
      VStack {
         if (self.myClass.screen == "main") {
            MainView()
         } else if (self.myClass.screen == "detail") {
            DetailView()
         }
      }
   }

But as you see, is not pretty. And I don't get any animations when changing screens.

Does anyone have an idea how to do this or how should I approach this situation?

Your second approach is correct. You just need animations. Unfortunately they only work when changing @State variables.

For this you need to create a new @State variable and assign it in .onReceive :

struct ContentView: View {
    @EnvironmentObject var myClass: MyClass
    
    @State var screen: String?

    var body: some View {
        VStack {
            if screen == "main" {
                MainView()
            } else if screen == "detail" {
                DetailView()
            }
        }
        .onReceive(myClass.$screen) { screen in
            withAnimation {
                self.screen = screen
            }
        }
    }
}

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