Bidirectional binding with Picker
In this section, we will use Picker
and a bound state variable to allow the user to choose one color from a group of five choices. Take a look at the following example:
import SwiftUI struct StateWithPicker: View { private let colors = ["White", "Red", "Blue", "Green", "Black"] @State private var color = "White" var body: some View { VStack(spacing: 15) { Spacer() Text("Choose your color by name") Picker("Name", selection: $color) { ForEach(colors, id: \.self) { name in Text("\(name)") } } .padding(.horizontal) Button("Click here to reset your choice") { color = "White" }.font(.title3) Spacer() Text("Selected color: \(color)") .padding() Spacer() } .font(.title) } } struct Previews_ContentView_Previews: PreviewProvider { static var previews: some View { StateWithPicker() } }
Notice that the binding to Picker
is completely bidirectional: the button press will reset the selected color to White
, and this will update the selection shown by Picker
as well.
Text
is instead bound in “read-only mode” (as text labels are not normally capable of editing their own content).
The following image shows Picker
in action within the simulator:
Figure 3.6 – Picker inside the simulator
In the next section, we will complete our description of @Binding
, @ObservableObject
, and @StateObject
.