How to update ContainerViewController from several VC's?

Viewed 37

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.

  • I know I can use protocols and delegates, but then I have to set the delegate in each view
  • I know I can find the child VC (Updating Content In Container View), but since I have two containers for each TabBarItem, I would have to traverse child/parent back and forth to update correctly (Adding to Cart happens in large VC (see attached img) and CartPreview is the small one. If these two don't have a relationship with each other, I have to go from large to parent, then parent to child (small).

A part of the storyboard:

Storyboard

Container VC

    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!

1 Answers

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
}
Related