In part 2 we created a view with a list of products using MVVM and observables.
Now, let's build a view to display the product details, and to navigate to this new screen we are going to use a navigation link.
https://developer.apple.com/documentation/swiftui/navigationlink
Update the model
Our model will need additional properties to display product detail, here's how it look like now:
struct Product : Identifiable {
//MARK: - Properties
var id = UUID()
var description: String
var detail: String
var price: Double
}
extension Product {
//MARK: - Default initialization
init() {
self.description = "New product"
self.detail = "Detailed information"
self.price = 999.99
}
}
New screen
The new screen will display the product model properties.
It's just a simple list of data:
struct ProductDetailView: View {
let description: String
let detail: String
let price: Double
var body: some View {
List {
HStack {
VStack {
Text("Description:")
}
VStack {
Text(description)
}
}
HStack {
VStack {
Text("Detail:")
}
VStack {
Text(detail)
}
}
HStack {
VStack {
Text("Price:")
}
VStack {
Text(String(price))
}
}
}
.navigationBarTitle("Product detail")
}
}
Notice that I declared these properties in this screen:
let description: String
let detail: String
let price: Double
This means that when we call this view, we need to send the values for these properties in order to display them in the screen.
The navigation link
The navigation link is what will enable us the open the new screen by tapping a product that is displayed in the first list.
We need to place this navigation link for each product that will be displayed in the list. This means, inside the foreach loop:
- Before navigation link:
ForEach(viewModel.productList) { product in
Text("Description: " + product.description)
}
- After navigation link
ForEach(viewModel.productList) { product in
NavigationLink(product.description, destination: ProductDetailView(description: product.description, detail: product.detail, price: product.price))
}
Final result
Alright, after completing these changes our navigation to the new screen should be ready.
You can download the updated version and play the result for yourself: Github
Top comments (0)