Немого передать результат во второе View
Вопрос заключается в передачи результат из ViewModel в любое View
Mоя Model
struct ItemsModel: Codable {
var item1: String = ""
var item2: String = ""
}
View
struct ContentView: View {
@ObservedObject var resultViewModel = CalcViewModel()
@State var isResultView: Bool = false
var body: some View {
NavigationView {
Form {
Section(header: Text("Ввод значения")) {
TextField("Введите число", text: $resultViewModel.itemModel.item1)
TextField("Введите число", text: $resultViewModel.itemModel.item2)
}
Section (header: Text("Ответ")) {
Text("\(resultViewModel.resultCalc())")
}
Button(action: {
self.isResultView.toggle()
}, label: {
Text("Рассчитать")
})
}
.sheet(isPresented: $isResultView) {
ResultView()
}
.navigationBarTitle(Text("Calculate"))
}
}
}
ViewModel
class CalcViewModel: ObservableObject {
@Published var itemModel = ItemsModel()
var item1Double: Double {
return Double(itemModel.item1) ?? 0
}
var item2Double: Double {
return Double(itemModel.item2) ?? 0
}
func resultCalc() -> Double {
let resultDouble = item1Double + item2Double
print("? \(resultDouble)")
return resultDouble
}
}
View куда надо передать результат
struct ResultView: View {
@StateObject var vm = CalcViewModel()
var body: some View {
Text("Ответ: \(vm.resultCalc())")
}
}
Ответы (1 шт):
Автор решения: Andrew
→ Ссылка
Есть два варианта. Попроще передавать в конструктор:
...
let model:CalcViewModel
...
init(model:CalcViewModel){
self.model = model
}
...
второй вариант, в View в котором заполняется модель, добавляете:
var body: some View {
NavigationView {
Form {
Section(header: Text("Ввод значения")) {
TextField("Введите число", text: $resultViewModel.itemModel.item1)
TextField("Введите число", text: $resultViewModel.itemModel.item2)
}
Section (header: Text("Ответ")) {
Text("\(resultViewModel.resultCalc())")
}
Button(action: {
self.isResultView.toggle()
}, label: {
Text("Рассчитать")
})
}
.sheet(isPresented: $isResultView) {
ResultView()
}
.navigationBarTitle(Text("Calculate"))
}.environmentObject(resultViewModel)
}
и там где вам нужно модель получить:
struct ResultView: View {
@EnvironmentObject vm:CalcViewModel
var body: some View {
Text("Ответ: \(vm.resultCalc())")
}
}
вот есть пример если абстрагироваться от вашего кода использование environmentObject:
// Our observable object class
class GameSettings: ObservableObject {
@Published var score = 0
}
// A view that expects to find a GameSettings object
// in the environment, and shows its score.
struct ScoreView: View {
@EnvironmentObject var settings: GameSettings
var body: some View {
Text("Score: \(settings.score)")
}
}
// A view that creates the GameSettings object,
// and places it into the environment for the
// navigation view.
struct ContentView: View {
@StateObject var settings = GameSettings()
var body: some View {
NavigationView {
VStack {
// A button that writes to the environment settings
Button("Increase Score") {
settings.score += 1
}
NavigationLink(destination: ScoreView()) {
Text("Show Detail View")
}
}
.frame(height: 200)
}
.environmentObject(settings)
}
}