Корзина еды переопределяется - PullRequest
0 голосов
/ 15 мая 2018

Я работаю над приложением доставки, но у меня возникли некоторые проблемы с моей корзиной. Проблема заключается в следующем: каждый раз, когда покупатель добавляет новый товар в свою корзину, все в корзине получает имя самого последнего товара. Он только перезаписывает объект tableView и не влияет на мой бэкэнд, поэтому я знаю, что что-то неправильно импортировано.

Для Clarity у меня есть две таблицы: продукт и размер продукта, который я ввожу через JSON:

Файл продукта:

import Foundation
import SwiftyJSON

class Product {
    //This pulls the information per product. Edit information here and attach to each Restaurant cell.

    var id: Int?
    var name: String?
    var short_description: String?
    var image: String?
    var type: String?
    var size: String?

    init(json: JSON) {
        self.id = json["id"].int
        self.name = json["name"].string
        self.short_description = json["short_description"].string
        self.image = json["image"].string
        self.type = json["course"].string
    }
}

Размер продукта:

import Foundation
import SwiftyJSON

class ProductSize {
    //Label for product information

    var price:Float?
    var sizeId: Int?
    var size: Int?
    var product_id: Int?

    init(json: JSON) {
        self.price = json["price"].float
        self.sizeId = json["id"].int
        self.size = json["size"].int
        self.product_id = json["product_id"].int
    }

Еда передается нам от предыдущего контроллера представления здесь:

   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "cartInfo" {
     
            let controller = segue.destination as! CartController
            controller.product = product
            
        }
    }
    

В контроллере корзины я отображаю все блюда в корзине, но он появляется снова и снова с одним и тем же приемом пищи.

    var product: Product?

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "shoppingCartCell", for: indexPath) as! CartCell

            let cart = Cart.currentCart.items[indexPath.row]
            let pname = product?.name
            cell.lblQty.text = "\(cart.qty)"
            cell.lblTotal.text = "$\(cart.productSize.price! * Float(cart.qty))"
            cell.lblName.text = pname



        return cell

На странице вывод выглядит так:

enter image description here

Прямо сейчас, если вы закажете гамбургер, а затем положите чизбургер в свою тележку, он придет как два чизбургера. Что я могу сделать, чтобы отобразить нужную информацию для всех товаров в корзине?

Вот табличное представление, которое заполняет все:

//Populate products in cart.
extension CartController: UITabBarDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return    Cart.currentCart.items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "shoppingCartCell", for: indexPath) as! CartCell
        
            let cart = Cart.currentCart.items[indexPath.row]
            let pname = self.product
            cell.lblQty.text = "\(cart.qty)"
            cell.lblTotal.text = "$\(cart.productSize.price! * Float(cart.qty))"
            cell.lblName.text = pname?.name

        
        
        
        return cell

        
    }
    
    
    
    
}

1 Ответ

0 голосов
/ 15 мая 2018

Повторение названия продукта означает только одно: product - это не массив продуктов, это один продукт, поэтому product?.name будет отображаться. И, очевидно, вы устанавливаете переменную product в классе Cart из предыдущего VC, вместо этого вы должны сделать массив product и добавить его к предыдущему контроллеру представления.

Вся структура сбивает с толку, может быть, вы путаете cart с product в func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...