我似乎无法让我的自定义 collectionView Cell 可见。我知道 CollectionView 出现是因为我更改了属性检查器的背景颜色,但自定义单元格没有出现。我在属性检查器中设置了约束,并在图像下方有一个水平堆栈 View 。
我完全按照 Udemy 类(class)的指导进行操作,但它似乎不起作用。这就是我配置单元格的方式:
代码如下:
import UIKit
class ListVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var productsCollection: UICollectionView!
private(set) public var products = [Product]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
productsCollection.dataSource = self
productsCollection.delegate = self
}
func initProducts(Product: Product) {
products = DataService.instance.getGroceryOptions()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return products.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProductCell", for: indexPath) as? ProductCell {
let product = products[indexPath.row]
cell.updateViews(product: product)
return cell
}
return ProductCell()
}
}
这是 ProductCell 的实现:
class ProductCell: UICollectionViewCell {
@IBOutlet weak var itemImage: UIImageView!
@IBOutlet weak var productName: UILabel!
@IBOutlet weak var productPrice: UILabel!
@IBOutlet weak var calCount: UILabel!
func updateViews(product: Product){
itemImage.image = UIImage(named: product.imageName)
productName.text = product.title
calCount.text = product.cal
productPrice.text = product.price
}
}
这是数据服务的实现:
class DataService {
static let instance = DataService()
private let item = [
Product(title: "Eggs", price: "4.94", imageName: "eggs.jpeg", cal: "340"),
]
private let Groceries = [Product]()
func getGroceryOptions() -> [Product] {
return Products
}
}
这是产品实现:
struct Product {
private(set) public var title: String
private(set) public var price: String
private(set) public var imageName: String
private(set) public var cal: String
init(title: String, price: String, imageName: String, cal: String) {
self.title = title
self.price = price
self.imageName = imageName
self.cal = cal
}
}
最佳答案
1) 您的 initProducts
方法没有在代码中的任何地方被调用。
2) 更新数据源后必须调用collectionView.reloadData()
。这意味着,您必须在更新 products
属性后调用此方法。
3) 此外,正如其他人在他们的回答中提到的那样,似乎您的 getGroceryOptions()
方法实际上应该返回 items
而不是 Products
(那是什么,顺便说一句?)。
关于ios - 如何使自定义 collectionview 单元格可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48672335/