【问题标题】:Show image in Xcode based on Firestore boolean value基于 Firestore 布尔值在 Xcode 中显示图像
【发布时间】:2021-03-02 15:36:13
【问题描述】:

我是编码新手,真的可以使用您的帮助! 我试图在基于布尔值的产品上显示“畅销书”图像。 我正在为数据库使用 Firestore。 我已经设法在所有文档上获得了“畅销书”字段的值,但我不知道下一步该做什么。 到目前为止,这是我的代码。这显示了所有产品的 bestsellerImg - 而不仅仅是 value = "True" 的产品

这里有两张图片来说明我的意思:)

swift 文件/类“ProductsVC”正在控制 ViewController,其中包含 collectionView。

来自“ProductsVC”的代码

import UIKit
import Firebase

class ProductsVC: UIViewController, ProductCellDelegate {

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var categoryName: UILabel!
    
    var products = [Product]()
    var category: Category!
    var db : Firestore!
    var listener : ListenerRegistration!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        db = Firestore.firestore()
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UINib(nibName: Identifiers.ProductCell, bundle: nil), forCellWithReuseIdentifier: Identifiers.ProductCell)
        setQuery()
        categoryName.text = category.name

    }
    

    
    func setQuery() {
        
        var ref: Query!
        ref = db.products(category: category.id)
        listener = ref.addSnapshotListener({ (snap, error) in
            
            if let error = error {
                debugPrint(error.localizedDescription)
            }
            snap?.documentChanges.forEach({ (change) in
                let data = change.document.data()
                let product = Product.init(data: data)
                
                switch change.type {
                case .added:
                    self.onDocumentAdded(change: change, product: product)
                case .modified:
                    self.onDocumentModified(change: change, product: product)
                case .removed:
                    self.onDoucmentRemoved(change: change)
                
                }
            })
        })
    }
    
    
    
    func productAddToCart(product: Product) {
        if UserService.isGuest {
            self.simpleAlert(title: "Hej!", msg: "Man kan kun tilføje ting til sin kurv hvis man er oprettet som Fender-bruger. ")
            return
        }
        
        PaymentCart.addItemToCart(item: product)
        self.addedtocart(title: "Tilføjet til kurv!", msg: "")
    }
 
}

extension ProductsVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func onDocumentAdded(change: DocumentChange, product: Product) {
        let newIndex = Int(change.newIndex)
        products.insert(product, at: newIndex)
        collectionView.insertItems(at: [IndexPath(item: newIndex, section: 0)])
    }
    
    func onDocumentModified(change: DocumentChange, product: Product) {
        if change.oldIndex == change.newIndex {
            let index = Int(change.newIndex)
            products[index] = product
            collectionView.reloadItems(at: [IndexPath(item: index, section: 0)])
        } else {
            let oldIndex = Int(change.oldIndex)
            let newIndex = Int(change.newIndex)
            products.remove(at: oldIndex)
            products.insert(product, at: newIndex)
            
            collectionView.moveItem(at: IndexPath(item: oldIndex, section: 0), to: IndexPath(item: newIndex, section: 0))
            
        }
    }
    
    func onDoucmentRemoved(change: DocumentChange) {
        let oldIndex = Int(change.oldIndex)
        products.remove(at: oldIndex)
        collectionView.deleteItems(at: [IndexPath(item: oldIndex, section: 0)])
        
    
    }
    
    
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        products.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Identifiers.ProductCell, for: indexPath) as? ProductCell {
            
            cell.configureCell(product: products[indexPath.item], delegate: self)
            return cell
        }
        return UICollectionViewCell()
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vc = DetailProductVC()
        let selectedProduct = products[indexPath.item]
        vc.product = selectedProduct
        vc.modalTransitionStyle = .crossDissolve
        vc.modalPresentationStyle = .overCurrentContext
        present(vc, animated: true, completion: nil)
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = view.frame.width
        let cellWidth = (width - 30) / 3
        let cellHeight = cellWidth * 2.1

        return CGSize(width: cellWidth, height: cellHeight)
    }
    
    
    
    
}

我的结构

import Foundation
import FirebaseFirestore

struct Product {
    var name: String
    var id: String
    var category: String
    var price: Double
    var productDescription: String
    var imageUrl: String
    var timeStamp: Timestamp
    var inStore: Int
    var bestseller: Bool
    var quantity: Int
    
    init(
        name: String,
        id: String,
        category: String,
        price: Double,
        productDescription: String,
        imageUrl: String,
        timeStamp: Timestamp = Timestamp(),
        inStore: Int,
        bestseller: Bool,
        quantity: Int) {
        
        self.name = name
        self.id = id
        self.category = category
        self.price = price
        self.productDescription = productDescription
        self.imageUrl = imageUrl
        self.timeStamp = timeStamp
        self.inStore = inStore
        self.bestseller = bestseller
        self.quantity = quantity
    }
        init(data: [String: Any]) {
            name = data["name"] as? String ?? ""
            id = data["id"] as? String ?? ""
            category = data["category"] as? String ?? ""
            price = data["price"] as? Double ?? 0.0
            productDescription = data["productDescription"] as? String ?? ""
            imageUrl = data["imageUrl"] as? String ?? ""
            timeStamp = data["timeStamp"] as? Timestamp ?? Timestamp()
            inStore = data["inStore"] as? Int ?? 0
            bestseller = data["bestseller"] as? Bool ?? true
            quantity = data["quantity"] as? Int ?? 0
        }
        
        static func modelToData(product: Product) -> [String: Any] {
            
            let data : [String: Any] = [
                "name" : product.name,
                "id" : product.id,
                "category" : product.category,
                "price" : product.price,
                "productDescription" : product.productDescription,
                "imageUrl" : product.imageUrl,
                "timeStamp" : product.timeStamp,
                "inStore" : product.inStore,
                "bestseller" : product.bestseller,
                "quantity" : product.quantity
            ]
            
            return data
        }
    }

extension Product : Equatable {
    static func ==(lhs: Product, rhs: Product) -> Bool {
        return lhs.id == rhs.id
    }
}

来自“ProductCell”的代码

import UIKit
import Kingfisher
import Firebase

protocol ProductCellDelegate : class {
    func productAddToCart(product: Product)
}

class ProductCell: UICollectionViewCell{

    @IBOutlet weak var imgView: UIImageView!
    @IBOutlet weak var titleLbl: UILabel!
    @IBOutlet weak var priceLbl: UILabel!
    @IBOutlet weak var bestsellerImg: UIImageView!
    
    var db: Firestore?
    
    
    
    weak var delegate : ProductCellDelegate?
    private var product: Product!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        imgView.layer.cornerRadius = 5
        getInStore()
       }
    

    
    func getInStore() {
                Firestore.firestore().collection("products").getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents{
                    var isBestseller = document.get("bestseller")
                    
                }
            }
        }

    }
    
    
    
    func configureCell(product: Product, delegate: ProductCellDelegate) {
        self.product = product
        self.delegate = delegate
        
        titleLbl.text = product.name
        
        if let url = URL(string: product.imageUrl) {
            let placeholder = UIImage(named: "Fender")
            imgView.kf.indicatorType = .activity
            let options : KingfisherOptionsInfo =
                [KingfisherOptionsInfoItem.transition(.fade(0.1))]
            imgView.kf.setImage(with: url, placeholder: placeholder, options: options)
        }

    let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.currencyCode = "DKK"
        if let price = formatter.string(from: product.price as NSNumber) {
        priceLbl.text = price
        
        
        }
}
    
    @IBAction func addToCart(_ sender: Any) {
        delegate?.productAddToCart(product: product)

            
    }
    

    }

【问题讨论】:

  • 您的代码逻辑看起来不错,有什么错误行为?
  • 您的代码有点不确定。您将获得 products 集合中的所有文档 - 可能是 1 或 100。然后您将一次又一次地遍历每个文档并设置相同的类变量 self.bestsellerImg。我想如果你想让图像闪烁,那就可以了,但我猜这不是意图。
  • @Jay 感谢您抽出宝贵时间回答:) 那我该怎么办?我已经尝试了好几天不知道该怎么做..
  • @luca_999 它显示所有产品上的 bestsellerImg,而不是仅显示值为“true”的产品。谢谢你的时间:)
  • 你能澄清你的尝试吗?如果有 5 个文档,并且它们的 bestseller 属性设置为 true、true、false、false、false,那么 self.bestsellerImg. 将设置为 true,然后再次设置为 true,然后再设置为 false,然后再设置为 false 和 false。那么这样做的目的是什么?每个文档中是否存储了更多数据?这将是一个书籍清单或类似的东西吗?请记住,我们只知道您与我们分享的内容,因此如果您需要帮助,代码的目的需要非常明确。

标签: ios swift firebase google-cloud-firestore


【解决方案1】:

查看代码,可能有一个非常简单的解决方案可以简化您尝试做的事情。

让我介绍一下,然后提出建议:

tableView 数据源在 setQuery 函数中填充

func setQuery() { 
  ...
  snap?.documentChanges.forEach({ (change) in
     let data = change.document.data()
     let product = Product.init(data: data)

每个产品都知道它是否是畅销产品,因为它有一个畅销属性,即真假。因此,当从 firebase 加载产品时,该属性会使用 Product.init 进行设置。

因为您的 tableView 委托正在创建每个单元格

cell.configureCell(product: products[indexPath.item]

你为什么不在 ProductCell 中有一段代码说明如果产品是 bestSeller 则使用 bestSeller 图片,否则使用常规图片?

func configureCell(product: Product, delegate: ProductCellDelegate) {
   self.product = product
   self.delegate = delegate
   
   if self.product.bestSeller == true {
      //set the image the bestseller image
   } else {
      //set the image to the regular image
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-07
    • 2021-12-23
    • 1970-01-01
    • 2023-04-05
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多