SwiftUIMidOpen-ended
How do you pass data between a sheet and the parent view?
Explanation & Code
Answer:
Use @Binding to pass a two-way connection into the sheet, so changes inside the sheet reflect in the parent.
Code Example:
struct ParentView: View {
@State private var isSheetPresented = false
@State private var selectedColor = "Red"
var body: some View {
VStack {
Text("Selected: \(selectedColor)")
Button("Open Sheet") { isSheetPresented = true }
}
.sheet(isPresented: $isSheetPresented) {
ColorPickerSheet(selectedColor: $selectedColor)
}
}
}
struct ColorPickerSheet: View {
@Binding var selectedColor: String
@Environment(\.dismiss) var dismiss
var body: some View {
VStack {
ForEach(["Red", "Green", "Blue"], id: \.self) { color in
Button(color) {
selectedColor = color // updates parent
dismiss()
}
}
}
}
}
Rate your understanding: