1

I have a settings Viewmodel. When I am changing a published variable by Toogle it is Automatically going back to a previous view.

I am accessing that published variable in Content View to change the language of the app. If I do not access the published variable then in the Content view by environment object, changing published variable does not trigger Auto navigation.

Settings View:

struct User4View: View {
    
    @EnvironmentObject var settingsVM: SettingsViewModel
    
    var body: some View {
        VStack{
              HStack(spacing:12){
                    Image("language")
                        .resizable()
                        .frame(width:20,height: 20)
                    Text(AppStrings.language)
                        .mediumHeaderNotBoldTextStyle()
                    Spacer()
                    Text("EN")
                    Toggle("", isOn: $settingsVM.isBangla.didSet { (state) in
                            print(state)
                        settingsVM.gotoLoginScreen = false
                    })
                        .labelsHidden()
                        
                    Text("BN")
                }
    }

Settings ViewModel:

class SettingsViewModel:ObservableObject{
    
    @Published var viewrs:ViewersResponseModel?
    @Published var gotoLoginScreen:Bool = false
    
    //static var shared = SettingsViewModel()
    @Published var isBangla = UserDefaults.standard.object(forKey: "isBangla") as? Bool ?? false{
        didSet{
            
            UserDefaults.standard.set(isBangla, forKey:"isBangla")
            print("isBangla",UserDefaults.standard.object(forKey: "isBangla") as? Bool)
        }
    }

}

ContentView:

struct ContentView: View {
    @ObservedObject var settingsVM = SettingsViewModel()
    
    var body: some View {
        
        NavigationView{
                Admin2ViewWithoutForm()   
        }.navigationViewStyle(StackNavigationViewStyle())
        .environmentObject(settingsVM)
        .environment(\.locale, .init(identifier: settingsVM.isBangla ? "bn-BD" : "en"))
    }
}


            
                    

            
            
                    
Rob
  • 14,746
  • 28
  • 47
  • 65
Tanvirgeek
  • 540
  • 1
  • 9
  • 17
  • This needs a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). You code does not build. Please make sure you start a fresh project rather than editing code in your current project. However, the way you have this set up is probably the culprit. If you don't need the `SettingsViewModel()` in `ContentView()`, then just initial it in `User4View` as a Singleton instead of passing it as an `EnvironmentObject`. – Yrb Oct 22 '21 at 14:13
  • OK, I will come back with a fresh project. – Tanvirgeek Oct 25 '21 at 03:47

0 Answers0