I am currently working on a weight tracking app as a tutorial project for Swift. I am implementing the MVVM pattern, and I have a weightEntry
class, where one of the attributes is weight
, a Double
.
In my view I have one ViewModel object, which has a weightEntry
object. I would like to assign the entry in the Weight text field to my weightEntry.weight
, however I'm not sure how I could convert the format from string to double in the view?
Below is the code in the view:
@ObservedObject var mainViewVM = MainViewViewModel()
var body: some View {
VStack(alignment: .leading, spacing: /*@START_MENU_TOKEN@*/nil/*@END_MENU_TOKEN@*/, content: {
Text("Weight Tracking App").font(.title)
HStack {
Text("Add your current weight").font(.subheadline)
TextField("Weight", text: $mainViewVM.weightEntry.weight)
.padding()
.keyboardType(.decimalPad)
}
CodePudding user response:
There is a initializer which can take a Double
and a format description , init(_:value:format:prompt:)
.
TextField("Weight", value: $mainViewVM.weightEntry.weight, format: .number.precision(.fractionLength(1)))