-
Book Overview & Buying
-
Table Of Contents
SwiftUI Projects
By :
We are going to display a SwiftUI List view. Our List is going to display a list of colors. First, we need to create a color model.
Open the ColorModel file inside the Model folder and add the following:
struct ColorModel: Identifiable {
var id = UUID()
var name: String
}
This struct has two properties: id and name. We have also set our model so that it conforms to Identifiable. When using a List in SwiftUI, our List is required to be unique, and there are two ways to handle this. We can either pass data, for example, the name as our unique ID, or we can use UUID and use this as our ID. The more you work with SwiftUI, the more ways you will encounter to handle Identifiable. If your data was coming from a feed, then you could use id if it were unique.
Open ColorsView.swift and add the following code inside the ColorsView struct, before the body:
@State var colors: [ColorModel] = [ ColorModel(name: 'Red'), ColorModel(name: 'White'), ColorModel(name: 'Blue'), ColorModel(name: 'Black'), ColorModel(name: 'Pink'), ColorModel(name: 'Yellow') ]
Inside the body variable, replace Text('Hello World') with the following code:
List {
ForEach(colors) { color in // Step 1
NavigationLink(destination: EmptyView()) { // Step 2
Text(color.name) // Step 3
}
}
}
We just added another list; let's break down the rest of the code:
ForEach loop inside our List, and as it loops through the array, it gives us a color.ForEach loop creates a NavigationLink every time it loops through. NavigationLink is used to link to another page, but you might be wondering why you don't see EmptyView() in the folders. EmptyView() is an empty view that we get with SwiftUI and is excellent for prototyping. Using this allows us to deploy a simple placeholder that we can use until we create our actual detail view. For this example, we won't change it, but in later chapters, we will. Text(color.name) is our button label.We are finished setting up our Colors View. Hit Command + R and you should now see a list of colors where, when you tap on an item, it goes to a blank screen with a back button:
Figure 2.4
Instead of displaying an empty view, we can use a Text view to display our detail view. Update NavigationLink(destination: EmptyView()) to NavigationLink(destination: Text(color.name)). Now, if you build and run, you can tap on the color and will see it in the detail view.