in the Secondary
struct, the @Binding
property is secondTime
and I want it to initially have the value from the "parent".
But when I change the value in this struct, the time
property in the parent also changes. Is there a way to get the value from the parent but prevent any changes to the value from going back up to the parent?
struct ContentView: View {
@State var time: String = "";
var body: some View {
VStack {
Text("it is: \(time)")
Secondary(secondTime: $time)
Button("Change time") {
time = "2 poclock"
}
}
}
}
struct Secondary: View {
@Binding var secondTime: String;
var body: some View {
Text("secondary time is \(secondTime)")
Button("Change time again from Secondary View") {
secondTime = "3 oclock"
}
}
}
CodePudding user response:
In Secondary
use:
@State var secondTime: String
and in ContentView
use:
Secondary(secondTime: time)
not $time
EDIT1:
If you want to click the button in ContentView
to change both views,
but Secondary
only changes itself, then try this approach:
struct Secondary: View {
@Binding var secondTime: String
@State var localTime: String = ""
var body: some View {
Text("Secondary time is \(localTime)") // <--- here
.onChange(of: secondTime) { newval in // <--- here
localTime = newval // <--- here
}
Button("Change time again from Secondary View") {
localTime = "3 oclock " String(Int.random(in: 1..<100)) // <-- to show changes
}
}
}
struct ContentView: View {
@State var time: String = ""
var body: some View {
VStack (spacing: 55) {
Text("ContentView it is: \(time)")
Secondary(secondTime: $time)
Button("Change time") {
time = "2 oclock " String(Int.random(in: 1..<100)) // <-- to show changes
}
}
}
}