问题是将 ViewModel 的结果传递给任何 View
我的模特
struct ItemsModel: Codable {
var item1: String = ""
var item2: String = ""
}
看法
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"))
}
}
}
视图模型
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
}
}
查看将结果传递到哪里
struct ResultView: View {
@StateObject var vm = CalcViewModel()
var body: some View {
Text("Ответ: \(vm.resultCalc())")
}
}