Reputation: 35
My @Binding weight variable connects to my Source of Truth further up in my code. But I also need to let my user edit this with a TextField(). So, I am trying to create a local variable of type String because TextField requires type Bindable.
Perhaps I'm approaching this wrong.
struct SetsBar: View {
@Binding var weight: Int
@Binding var reps: Int
@State var weightString: String = String(weight)
init(weight: Binding<Int>, reps: Binding<Int>) {
self._weight = weight
self._reps = reps
}
var body: some View {
HStack {
TextField("\(weight)", text: $weightString)
}
}
}
I get an error on my @State property
Cannot use instance member 'weight' within property initializer; property initializers run before 'self' is available
Upvotes: 0
Views: 31
Reputation: 257493
You can bind weight
directly using TextField
variant with formatter (configuring formatter as much as needed, below is simplified variant for demo), like
var body: some View {
HStack {
TextField("\(weight)", value: $weight, formatter: NumberFormatter())
}
}
Upvotes: 1