Is it the real code or did you type it here ?
I noticed several errors:
var id: UUID()
soudé be
var id = UUID()
var body: Some View {
should be
var body: some View {
What is this closure after TextField (it is only supported in MacOS: https://stackoverflow.com/questions/58776561/add-label-to-swiftui-textfield):
TextField("xValue", value: $vars.xValue, format: .number) {
Text("X")
}
So here is a code that works and that is properly formatted with code formatter.
If that's OK, please close the thread by marking this answer as correct. Otherwise explain what's the problem.
@Observable class Variables: Identifiable {
var id = UUID() // <<-- Changed here
var xValue: Int = 1
var yValue: Int = 1
}
struct MainView: View {
@State var vars = Variables()
var body: some View {
VStack {
Subview()
.environment(vars)
.padding()
Text("Value X = \(vars.xValue)") // No $vars here
Text("Value Y = \(vars.yValue)")
}
}
}
struct Subview: View {
@Environment(Variables.self) private var vars
var body: some View {
@Bindable var vars = vars // <<-- Added here // https://developer.apple.com/documentation/swiftui/bindable
VStack {
HStack {
Text("X")
TextField("xValue", value: $vars.xValue, format: .number) /*{ Text("X") }*/ // <<-- Changed here
.textFieldStyle(.roundedBorder)
}
HStack {
Text("Y")
TextField("yValue", value: $vars.yValue, format: .number) /*{ Text("Y") }*/
.textFieldStyle(.roundedBorder)
}
}
}
}