首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >基于Firestore布尔值在Xcode中显示图像

基于Firestore布尔值在Xcode中显示图像
EN

Stack Overflow用户
提问于 2021-03-02 15:36:14
回答 1查看 87关注 0票数 0

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

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

swift文件/类"ProductsVC“控制包含collectionView的ViewController。

来自"ProductsVC“的代码

代码语言:javascript
运行
AI代码解释
复制
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)
    }
    
    
    
    
}

我的结构

代码语言:javascript
运行
AI代码解释
复制
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“的代码

代码语言:javascript
运行
AI代码解释
复制
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)

            
    }
    

    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-04 15:16:23

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

让我浏览一下,然后给出一个建议:

在setQuery函数中,tableView数据源填充为

代码语言:javascript
运行
AI代码解释
复制
func setQuery() { 
  ...
  snap?.documentChanges.forEach({ (change) in
     let data = change.document.data()
     let product = Product.init(data: data)

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

因为您的tableView代理正在创建每个单元格

代码语言:javascript
运行
AI代码解释
复制
cell.configureCell(product: products[indexPath.item]

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

代码语言:javascript
运行
AI代码解释
复制
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
   }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66442399

复制
相关文章
如何在Linux中使用管道将命令的输出传递给其他命令?
在Linux中,管道使用竖线符号 | 表示,它位于两个命令之间。管道的基本语法如下:
网络技术联盟站
2023/09/06
1.5K0
如何在Linux中使用管道将命令的输出传递给其他命令?
如何将多个参数传递给 React 中的 onChange?
在 React 中,一些 HTML 元素,比如 input 和 textarea,具有 onChange 事件。onChange 事件是一个非常有用、非常常见的事件,用于捕获输入框中的文本变化。有时候,我们需要将多个参数同时传递给 onChange 事件处理函数,在本文中,我们将介绍如何实现这一目标。
网络技术联盟站
2023/06/07
3K0
如何在Linux中使用管道将命令的输出传递给其他命令?
在Linux系统中,管道(Pipeline)是一种强大的工具,它允许将一个命令的输出作为另一个命令的输入。通过管道,我们可以将多个命令串联在一起,实现数据的流动和处理。本文将详细介绍如何在Linux中使用管道将命令的输出传递给其他命令,并提供一些常见的使用示例。
网络技术联盟站
2023/06/14
1.5K0
如何在Linux中使用管道将命令的输出传递给其他命令?
Vue 中,如何将函数作为 props 传递给组件
作者:Michael Thiessen 译者:前端小智 来源:medium 点赞再看,养成习惯本文 GitHub https://github.com/qq44924588... 上已经收录,更多往
前端小智@大迁世界
2020/05/18
8.4K0
Laravel实现redis发布-订阅
如果说我们需要一个比较简单的这种机制,我们可以采用redis这个轻量级的订阅机制,我们可以参考redis的 Publish/Subscribe 机制,得到比较好的问题解决方案 当然,如果是项目比较复杂,可以考虑使用Kafka, RabbitMQ之类的消息队列组件
憧憬博客
2020/07/20
1.3K0
react event事件订阅传值
event(事件订阅)是react新增的通信方式。它类似webSorcket和postMessage的通信方式,一边发送传值,另一边监听接收. 适合兄弟组件传值
心念
2023/01/11
5250
iframe怎么将参数传递给vue 父组件
在子页面的iframe中想将参数传递给Vue父组件,可以使用postMessage()方法将数据发送给父窗口。父组件可以通过监听message事件来接收并处理这些数据。
王小婷
2023/08/10
1.5K0
将多个属性传递给 Vue 组件的几种方式
所有使用基于组件的体系结构(如Vue和React)的开发人员都知道,创建可重用组件是很困难的,而且大多数情况下,最终会通过传入大量的属性,以便从外部更容易地控制和自定义组件。这并不坏,但是传递大量属性确实会变得有点麻烦和丑陋。
前端小智@大迁世界
2020/05/11
2K0
python接口测试:如何将A接口的返回值传递给B接口
一种方式是可以通过数据库来获取,但是通过这次接口测试,我发现读取数据库有一个缺点:速度慢
冰霜
2022/03/15
2.1K0
React篇(029)-如何将参数传递给事件处理程序或回调函数?
你可以使用箭头函数来包装事件处理器并传递参数: <button onClick={() => this.handleClick(id)} /> 这相当于调用 .bind: <button onClick={this.handleClick.bind(this, id)} />
齐丶先丶森
2022/05/12
3.9K0
Laravel如何优雅的使用Swoole
正在做一个智能家居的项目,接收下位机(就是控制智能家居硬件模块的HUB)协议解析,Web端维护硬件状态,利用APP交互。由于下位机数据是发送到服务器的XXX端口,所以必须对XXX端口进行监听。其实和聊天室的概念差不多,研究了一下workerman、swoole和其他几个开源的项目,决定采用swoole。
OwenZhang
2021/12/08
1.6K0
网络数据是如何传递给进程的
在用户态空间,调用发送数据接口 send/sento/wirte 等写数据包,在内核空间会根据不同的协议走不同的流程。以TCP为例,TCP是一种流协议,内核只是将数据包追加到套接字的发送队列中,真正发送数据的时刻,则是由TCP协议来控制的。TCP协议处理完成之后会交给IP协议继续处理,最后会调用网卡的发送函数,将数据包发送到网卡。
luoxn28
2020/05/18
1.6K0
程序员如何使用RSS订阅网站更新
很多国内程序员可能都有这种疑惑,去哪里看技术圈最新的消息?怎么知道厂都在用什么技术?做什么?怎么知道圈内最新的paper?怎么跟踪国内外技术大佬的博客?
伍六七AI编程
2021/05/17
2.2K0
微信下线模板消息,订阅通知如何使用?
指用户订阅一次,服务号可长期多次下发通知,长期订阅通知仅向政务民生、医疗等公共服务领域开放;
冷冷
2021/02/04
3.4K0
如何用RSS订阅?
我们常常会有订阅别人文章的需求,有更新的时候希望能有提醒的功能,RSS就是这样一个订阅的方式。
机智的程序员小熊
2019/01/12
4.9K0
如何用RSS订阅?
如何使用markdown书写微信订阅号素材?
我们知道,运营微信订阅号难免与编辑器打交道,而微信自带的编辑器,又有诸多的限制,如果一个人,一天,发一篇文章,花费在编辑格式,美化页面上的时间,就太可惜了。
程序员小助手
2020/04/08
1.7K0
laravel 中如何使用ajax和vue总结
最近写一个项目是基于laravel框架的,这个框架传言是为艺术而创作的优雅框架,简洁分明的风格,很吸引我,所以最近研究比较多。本次就是基于该框架然后将Vue插件加入实现一定的功能,vue插件本身强大,具体不说了,有兴趣的同学可以去官网
用户8449980
2021/07/13
2K0
如何正确使用 Composer 安装 Laravel 扩展包
正确使用 Composer 安装 Laravel 扩展包: 简单解释composer install如有 composer.lock 文件,直接安装,否则从 composer.json 安装最新扩展包和依赖;
全栈程序员站长
2022/07/08
1.7K0
点击加载更多

相似问题

Laravel Cashier -使用条带id取消订阅

51

使用Laravel Cashier & Stripe开始无卡订阅

21

Laravel Cashier -单个用户的多个订阅

15

使用Laravel & cashier直接从Stripe检查stripe订阅状态

21

如何使用Laravel Cashier获取订阅今天到期的所有用户

11
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档