SwiftUI - How to pass EnvironmentObject into View Model?

后端 未结 5 1992
甜味超标
甜味超标 2020-12-08 18:56

I\'m looking to create an EnvironmentObject that can be accessed by the View Model (not just the view).

The Environment object tracks the application session data, e

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 19:56

    You can do it like this:

    struct YourView: View {
      @EnvironmentObject var settings: UserSettings
    
      @ObservedObject var viewModel = YourViewModel()
    
      var body: some View {
        VStack {
          Text("Hello")
        }
        .onAppear {
          self.viewModel.setup(self.settings)
        }
      }
    }
    

    For the ViewModel:

    class YourViewModel: ObservableObject {
      
      var settings: UserSettings?
      
      func setup(_ settings: UserSettings) {  
        self.settings = settings
      }
    }
    

提交回复
热议问题