// // AddProductView.swift // CodigoBarrasInventario // // Created by David Grau Beltrán on 06/02/24. //
import SwiftUI
// Define a struct to represent each product struct Product { var name: String var code: String }
// Define a class to manage the inventory class Inventory: ObservableObject { @Published var products: [Product] = []
// Function to add a product to the inventory
func addProduct(name: String, code: String) {
let product = Product(name: name, code: code)
products.append(product)
}
}
// Define a SwiftUI view for adding products struct AddProductView: View { @State private var productName = "" @State private var productCode = "" @ObservedObject var inventory: Inventory
var body: some View {
VStack {
TextField("Enter Product Name", text: $productName)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
TextField("Enter Product Code", text: $productCode)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
Button("Add Product") {
if !productName.isEmpty && !productCode.isEmpty {
inventory.addProduct(name: productName, code: productCode)
productName = ""
productCode = ""
}
}
.padding()
Divider()
Text("Products in Inventory:")
.font(.headline)
.padding(.top)
List(inventory.products, id: \.code) { product in
VStack(alignment: .leading) {
Text("Name: \(product.name)")
Text("Code: \(product.code)")
}
}
.padding()
}
}
}
#Preview { AddProductView() }