I don't understand how to add an object via a button to the screen with goods.
I already have a product listing: https://i.stack.imgur.com/sqzrD.jpg
When I click on any of the products, I open the product information (conditionally) via .sheet, and then there are two buttons, close and add. https://i.stack.imgur.com/uvUs4.jpg close works, but I need to understand how to implement so that via add button the product is added to the view with Row style product display. Row of goods I have already created, there is CarManager logic:
import Foundation
class CartManager: ObservableObject {
@Published private(set) var products: [Product] = []
func addToCart(product: Product) {
products.append(product)
}
func removeFromCart(product: Product) {
products = products.filter { $0.id != product.id }
}
}
Here is the code itself, which is responsible for the .sheet when clicking on the product from the listing:
struct ProductDetailSheet: View {
let product: Product
@Binding var isSheetPresented: Product?
@State private var amount = 1
var body: some View {
VStack{
VStack {
Image(product.image)
Spacer()
Text(product.name)
.presentationDetents([.height(200)])
.presentationBackgroundInteraction(.enabled(upThrough: .medium))
}
HStack{
Button("Close") {
isSheetPresented = nil
}
Spacer()
Button("Add") {
isSheetPresented = nil
}
Spacer()
Stepper("Enter an amount: \(amount)", value: $amount, in: 0...200)
}
}
.padding()
}
}
#Preview {
PackingList()
}
Here is a piece of code of View with Row style product:
import SwiftUI
struct ProductRow: View {
var product: Product
var body: some View {
HStack(spacing: 20) {
Image(product.image)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 50)
.cornerRadius(10)
VStack(alignment: .leading, spacing: 10) {
Text(product.name)
.bold()
}
Spacer()
Image(systemName: "trash")
.foregroundColor(Color(hue: 1.0, saturation: 0.89, brightness: 0.835))
}
.padding(.horizontal)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
#Preview {
ProductRow(product: productRaid[0])
}
And I need to pass the product to this screen when I click on the .add button from the .sheet from the listing view.
import SwiftUI
struct Recommended: View {
var body: some View {
Text("1")
.foregroundStyle(.white)
}
}
#Preview {
Recommended()
}
How do I implement this? Which way to dig? I will be highly grateful to anyone who can share information on how I can implement this.
It should look like this on the screen. https://i.stack.imgur.com/HDyJA.png