Both View1 and View2 get the parameter text from the parent ContentView. But in View1 uses @Binding while View2 uses @State. Clicking View1 button will change the text value. However, after clicking, only the ContentView Text() updated, but View2 s Text does not update? why is that so?
From the print-out, both view1 and view2 calls init with the new value "View 1 Text".
Changing View2 to use @Binding will work to update View2 s text when it s updated.
Here s the sample code:
ContentView.swift
import SwiftUI
struct ContentView: View {
@State var showView1: Bool = false
@State var showView2: Bool = false
@State var text: String = "Hello World"
init() {
print("init ContentView")
}
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
Text("(text)")
HStack {
if showView1 {
View1($text)
}
if showView2 {
View2(text)
}
}
.border(.black)
HStack {
Button("View1") { showView1.toggle() }
Button("View2") { showView2.toggle() }
}
}
.padding()
}
}
View1.swift
struct View1: View {
@Binding var text: String
init(_ text: Binding<String>) {
self._text = text
print("init View1 (self.text)")
}
var body: some View {
Button("Click") {
print("Click view1 button")
self.text = "View 1 Text"
}
}
}
View2.swift
struct View2: View {
@State var text: String
init(_ text: String) {
self.text = text
print("init View2 (self.text)")
}
var body: some View {
VStack {
Button("Click") {
print("Click view2 button")
}
Text("view2 text : (text)")
}
}
}