SwiftUI 将 Int 值传递给 ViewModel
Posted
技术标签:
【中文标题】SwiftUI 将 Int 值传递给 ViewModel【英文标题】:SwiftUI pass Int value to the ViewModel 【发布时间】:2021-06-06 15:14:47 【问题描述】:我正在尝试将 Int 传递给 ViewModel,但它不起作用。 Value 仍然是 0。Strings 或 Data 对象没有问题,但是 Int、Double 和其他数字值仍然是 0 值。我也试过这种方式:
@Published var tankCapacity: Int?
但还是一样。如何解决?使用字符串并转换为给定类型?
AddVehicleView:
import SwiftUI
struct AddVehicleView: View
@ObservedObject var viewModel: AddVehicleViewModel
@State private var selected = 0
@State private var showingAlert = false
init(viewModel: AddVehicleViewModel)
self.viewModel = viewModel
UITableView.appearance().backgroundColor = .clear
UITableView.appearance()
var body: some View
VStack(alignment: .leading)
Text("Add new vehicle")
.font(.system(size: 26, weight: .medium))
.padding(.top, -30)
.padding(.leading, 20)
VStack
TextField("Brand/Model etc", text: $viewModel.name)
.padding(.top, 10)
.padding(.leading, 20)
.padding(.trailing, 20)
.font(.system(size: 20))
.textFieldStyle(RoundedBorderTextFieldStyle())
TextField("Capacity", value: $viewModel.tankCapacity, formatter: NumberFormatter()) // I am trying send int value from here
.padding(.top, 30)
.padding(.leading, 20)
.padding(.trailing, 20)
.font(.system(size: 20))
.textFieldStyle(RoundedBorderTextFieldStyle())
Form
Section
Picker("Fuel type", selection: $viewModel.fuelType)
ForEach(0 ..< viewModel.fuels.count)
Text(self.viewModel.fuels[$0]).tag($0)
.padding(.leading, 5)
.padding(.trailing, 5)
.padding(.leading, 5)
.padding(.trailing, 5)
Button("Add")
if self.viewModel.name.isEmpty
self.showingAlert = true
else
self.viewModel.saveVehicle()
self.viewModel.name = ""
.frame(width: 200, height: 50)
.background(Color.blue)
.font(.system(size: 20, design: .default))
.foregroundColor(Color.white)
.cornerRadius(10)
.padding(.top, -350)
.alert(isPresented: $showingAlert)
Alert(title: Text("Warning!"), message: Text("Fill the fields"))
Spacer()
导入基础
class AddVehicleViewModel: ObservableObject
@Published var name = ""
@Published var tankCapacity = 0 // and here I am trying to get value.
@Published var fuelType = 0
@Published var fuels = ["Petrol", "Diesel"]
private let persistenceService: PersistenceServiceProtocol
init(persistenceService: PersistenceServiceProtocol)
self.persistenceService = persistenceService
func saveVehicle()
print("name: \(name)")
print("tankCapacity: \(tankCapacity)")
let vehicle = Vehicle(name: name,
tankCapacity: tankCapacity)
do
try self.persistenceService.addVehicle(vehicle: vehicle)
catch
print("ADDVEHICLEMODEL saveVehicle Error")
【问题讨论】:
你在哪里修改 tankCapacity 值? 到 ViewModel。我编辑了代码。 View 和 ViewModel 粘在一起了。 【参考方案1】:在调用saveVehicle
之前,您需要先提交TextField(按回车键)。
如果您改为在视图模型中使用以下内容:
@Published var tankCapacityText = ""
didSet
tankCapacity = Int(tankCapacityText) ?? 0
@Published var tankCapacity = 0
在你看来:
TextField("Capacity", text: $vm.tankCapacityText)
那么用户就不需要回车了。
【讨论】:
以上是关于SwiftUI 将 Int 值传递给 ViewModel的主要内容,如果未能解决你的问题,请参考以下文章
在 MVC 5 中,如何将表对象数据作为列表传递给控制器视图模型?
SwiftUI 将数据从 UIViewRepresentable 传递给 SwiftUI 的 View