我是编程新手,真的需要你的帮助!我试图在一个基于布尔值的产品上展示一个“畅销”的形象。我正在为数据库使用Firestore。我已经设法在所有文档上获得了“畅销书”字段的值,但我不知道下一步该做什么。到目前为止,这是我的代码。这将显示所有产品的bestsellerImg -而不仅仅是值= "True“的产品。
这里有两张图片来说明我的意思:)
swift文件/类"ProductsVC“控制包含collectionView的ViewController。
来自"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)
}
}
发布于 2021-03-04 15:16:23
看一下代码,可能会有一个非常简单的解决方案,可以简化您正在尝试做的事情。
让我浏览一下,然后给出一个建议:
在setQuery函数中,tableView数据源填充为
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
}
https://stackoverflow.com/questions/66442399
复制相似问题