Reputation: 143
I've added a small container view to most of my app's VC's that will function as a Cart Preview, showing number of items in cart and total amount. Adding stuff to cart can be done from multiple places inside the app, so I'm looking to find the best option to update the container VC when is happens. I assume there's a better way than finding the correct VC and calling an update function from all places I can add to cart? Is it possible to keep a shared instance of the VC?
I've found some posts about this, but since I can update the cart from many places (VC's, Cells, JSON etc) I'm looking for the easiest one to maintain.
override func viewWillAppear(_ animated: Bool) {
updatePreviewBar()
}
func updatePreviewBar() {
numberOfItemsInCartLabel.text = "\( String(Cart.sharedInstance.order.items.count)) items"
amountLabel.text = String(Cart.sharedInstance.order.total.withTousandSeparator)
}
Thanks in advance!
Upvotes: 2
Views: 43
Reputation: 5223
You can use property observer and send a notification when the order total value has been changed.
extension Notification.Name {
static let cartUpdate = Notification.Name(
rawValue: "cartUpdate")
}
struct Cart {
static var orderTotal = 0.0 {
didSet {
NotificationCenter.default.post(name: .cartUpdate, object: nil)
}
}
}
Then in your CartContainerVC, you can put an observer for notification which will be called when the orderTotalValue changes.
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(updateCart), name: .cartUpdate, object: nil)
}
@objc func updateCart() {
// this function will be called whenver cart value changes. update your textfields here
}
Upvotes: 2