@binding
import SwiftUI
struct ParentView: View {
@State private var text: String = "Initial Text"
var body: some View {
VStack {
ChildView(text: $text) // 传递绑定
Text("Parent Text: \(text)") // 显示父视图的文本
.padding()
}
}
}
struct ChildView: View {
@Binding var text: String // 使用 @Binding 接收父视图的状态
var body: some View {
VStack {
TextField("Enter text", text: $text) // 修改 @Binding 会更新父视图的状态
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
Button("Change Parent Text") {
text = "Updated from Child" // 更新 @Binding 会反映到父视图
}
}
}
}Last updated