Показывать этикетку с количеством, когда товар находится в корзине (Swift 5) - PullRequest
0 голосов
/ 07 августа 2020

Когда пользователь добавляет товар в корзину. Выбранный товар должен показывать кнопки увеличения и уменьшения. и другие продукты должны показывать только кнопку добавления. Вы можете проверить это изображение

введите описание изображения здесь

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

Вот мой код

Product TableView

func getCartDetails()
    {
        ApiCaller().getData(url: get_cart_url, resultType: CartResult.self) { (results) in
            self.iddd = results.result!.id
            self.c = results.result!
            guard let resultArray = results.result?.cartItems as? [CartItem] else {return }
            UserDefaults.standard.set(results.result?.cartItems.count, forKey: "totalItemsInCart")
            
            for cart in resultArray
            {
                
                self.cAr.append(cart)
                
            }
            
            
            
        }
        
    }


func addItem(prodId:String,qty:Int,cartId:String)
    {
 
        let request = cartProducts(products: [addCartProducts(prodId:prodId, q: qty + 1)])
        
        do
        {
            let encodedResult = try JSONEncoder().encode(request)
            
            ApiCaller().postData(url: update_cart_url+cartId+"/update", requestBody: encodedResult, requestMethod: "PUT", resultType: UpdateCartResults.self) { (results) in
                print(results.statusCode)
              
                
                DispatchQueue.main.async {
                   

                    self.tableView.reloadData()
                }
                
            }
            
            
        }catch {
            print(error)
            return
        }
            
        
    }


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

        cell.generateCells(products: productArray[indexPath.row])
        
 
        let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: rupee + "\(productArray[indexPath.row].mrpAfterDiscount)")
        attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 1, range: NSMakeRange(0, attributeString.length))
        
        cell.secondPriceLbl.attributedText = attributeString
        
        cell.addBtnLbl.tag = indexPath.row
        
        


let productAtIndex = self.productArray[indexPath.row]

          
        
        if cAr.contains(where: { (item) -> Bool in
            productAtIndex.id == item.id
        }){
            // product is in cart, show increment/decrement button
            
             cell.addBtnLbl.isHidden = true
        } else {
            // product not in cart, show add button
            
             cell.addBtnLbl.isHidden = false
        }
        
        cell.callBackForAddButtonHidden = {
        
            cell.addBtnLbl.isHidden = true
            guard self.c != nil else {
                print("Creating cart for the first time")
                self.createCart(prodId: self.productArray[indexPath.row].id, qty: 1)
                return
                
            }
                self.addItem(prodId: self.productArray[indexPath.row].id, qty: 0, cartId: self.c!.id)
        }
        
    
        cell.selectionStyle = .none
        
        return cell
    } 

Вот моя ячейка TableView продукта, которую я пробовал использовать сравнивая cartDetails и productDetails, но это не сработало, поэтому я прокомментировал это.

func generateCells(products:Product)
    {
        self.productNameLbl.text = products.name
        self.productDescriptionLbl.text = products.additionInfo
        self.productPriceLbl.text = rupee + String(products.productMRP)

        if products.discountPercentage != 0
        {
        self.discountLbl.text = "\(products.discountPercentage)% Off"
        } else {
            self.discountLbl.isHidden = true
        }
        //

//        if products.id == cartDetails.id
//        {
//            addBtnLbl.isHidden = true
//            self.quantityLbl.text = "\(cartDetails.qty)"
//        } else {
//            addBtnLbl.isHidden = false
//        }
        
        
        self.productImgView.sd_setImage(with: URL(string: products.imgURL)) { (image, error, cache, url) in
            
        }
        
    }

1 Ответ

1 голос
/ 11 августа 2020

Предполагая, что ваша карта представляет собой массив Product, вы можете проверить в своем cellForRowAt indexPath, присутствует ли элемент с текущим индексом в вашей корзине, и отобразить / скрыть кнопки соответственно.

let productAtIndex = self.productArray[indexPath.row]

    if cart.contains(where: { (item) -> Bool in
        productAtIndex.id == item.id
    }){
        // product is in cart, show increment/decrement button
    } else {
        // product not in cart, show add button
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...