'SwiftUI: Change Binding's Value from Button's Action
I have a cart item detail view with the "Add To Order" button. I want to increase the number of items (cartItem.count) when the button is tapped and wonder why this code doesn't update the UI (Text("(cartItem.count)")):
import SwiftUI
struct CartItemDetail: View {
@Binding var cartItem: CartItem
var body: some View {
VStack {
Text("\(cartItem.count)")
Text(cartItem.product.name)
.font(.largeTitle)
cartItem.product.image
.resizable()
.frame(width: 200, height: 200).clipShape(Circle())
Text("\(cartItem.product.price) | \(cartItem.product.calories)")
Text(cartItem.product.description)
.multilineTextAlignment(.center)
.padding(.all, 20.0)
Button(action: {
cartItem.count = cartItem.count + 1
})
{
RoundedButton(imageName: "cart.badge.plus", text: "Add to order")
}
}
}}
Some more code (if needed to reproduce)
struct ContentView: View {
@ObservedObject var cart: Cart
var body: some View {
NavigationView {
List($cart.cartItems) { $cartItem in
NavigationLink(destination: CartItemDetail(cartItem: $cartItem)
) {
CartItemRow(cartItem: $cartItem)
}
}
}.navigationTitle("Cart")
}}
Cart and CartItem's code:
class Cart: ObservableObject {
@Published var cartItems: [CartItem]
init() {
self.cartItems = []
for product in testDataProducts {
cartItems.append(CartItem(product: product, count: 1))
}
}}
class CartItem: Identifiable {
var id: String
var product: Product
var count: Int
init(product: Product, count: Int) {
self.id = UUID().uuidString
self.product = product
self.count = count
}}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
