I have a restaurant app with MenuViewController
, DetailViewController
( all the details about food chosen from MenuViewController
) and CartViewController
. Now in DetailViewController
i got a button (add to cart), pressing on which i want the food from DetailViewController
to pass (to add ) to the CartViewController
. Please help guys! Any ideas on how one can handle it?
答案 0 :(得分:0)
I can suggest two approaches:
(Longer but robust Approach) Using Core Data: Add a new Product
object to Cart
entity. In your CartViewController, use NSFetchedResultsController
that will automatically receive changes made to the entity and update the view accordingly (keeping in mind that you're using the same managed object context)
(Simpler Approach) Using Delegates: Maintain a global array that will contain product elements. Add or remove elements from that array. Keep a delegate function like didUpdateCart
that notifies your CartViewController to update it's view with the current elements in the global products array.
Hope that helped.
答案 1 :(得分:0)
If I understand the question you can do somthing like this:
First add method setFood
to your CartViewController
:
class CartViewController: UIViewController {
func setFood(food: Food) {
// Here do with `food` somthing you want
}
}
Second in your DetailViewController
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let cartViewController = segue.destinationViewController as? CartViewController {
// food is your some object you need to transfare
cartViewController.setFood(food)
}
}
Or if you create your CartViewController
without storyboard in button action method you can do this in your DetailViewController
:
...
var cartViewController: CartViewController?
...
@IBAction func buttonAction(sender: AnyObject) {
cartViewController = CartViewController()
cartViewController.setFood(food)
self(cartViewController, animated: true, completion: nil)
}
...