Leave a rating/review
In this challenge, you’ll get a chance to practice using State and Bindings.
Open up the starter project, and see if you can get it working. There will be some directions and hints in the comments for you.
OK! Let’s see a way to solve this.
First, the directions say
Follow the TODO’s and errors to complete this challenge and get the project compiling.
Figure out where to use the @State and @Binding attributes
Pass the right data into the StatusControl and StatusIcon views
And finally Test out your solution with the Live View in the Canvas!
So, I’ll start at the top
These 3 properties will need an attribute added…
This is our main view. And it looks like both of these little subviews will need access to this data. So I want this data to live in ContentView.
I can use @State to do that, and also make them private properties to enforce that they can’t be accessed anywhere else.
struct ContentView: View {
🟢@State private❤️ var name: String = ""
🟢@State private❤️ var favoriteColor: Color = .green
🟢@State private❤️ var mood: Mood = .happy
I’m going to skip this part for now, and come back to it.
Down in the StatusControl view, I see that these three familiar properties will also need an attribute added.
This time, you’re going to be passing in data that is stored somewhere else. So it’s time for the Binding attribute
struct StatusControl: View {
🟢@Binding var name: String
🟢@Binding var favoriteColor: Color
🟢@Binding var mood: Mood
Now I can pass those bindings right into the controls below with dollar sign syntax.
var body: some View {
VStack {
TextField("Name", text: 🟢$name)
ColorPicker("Favorite Color", selection: 🟢$favoriteColor)
Picker("Mood", selection: 🟢$mood) {
This other custom view on the bottom doesn’t actually need any work. It’s just there to display the data that’s set, and won’t change anything.
So I can go back up to the top…
And “Pass the right kind of data into each view”
var body: some View {
VStack {
StatusControl🟢(name: $name, favoriteColor: $favoriteColor, mood: $mood)
.padding()
StatusIcon🟢(name: name, favoriteColor: favoriteColor, mood: mood)
.padding()
}
}
}
Now, I’ll test this all out with the Live View!
Set a Name
A favorite color
And a mood
And there’s my customized status icon!