[英]How do I make a custom collectionview cell visible?
我似乎無法使我的自定義collectionView Cell可見。 我知道出現了CollectionView,因為我更改了屬性檢查器上的背景顏色,但是自定義單元格沒有出現。 我在屬性檢查器中設置了約束,並在圖像下方有一個水平的堆棧視圖。
我完全按照Udemy課程的指示進行操作,但似乎不起作用。 這是我配置單元格的外觀:
代碼如下:
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
}
}
這是DataService實現:
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
}
}
您的initProducts
方法未調用。 由於此products
數組保持為空,因此您在集合中看不到任何單元格。
您應該調用initProducts
(例如,在viewDidLoad
),以用將在您的集合中顯示的元素填充products
數組。
還可以考慮從此函數中刪除參數(由於您不在此方法中使用參數,因此您不需要那里的參數)。 它應該看起來像:
func initProducts() {
products = DataService.instance.getGroceryOptions()
}
另外,您應該更正getGroceryOptions
方法。 它應該返回注釋中指出的item
。
在其他collectionView
函數之前,您是否有numberOfSectionsInCollectionView
節?
看一下這個例子:
func numberOfSectionsInCollectionView(collectionView:UICollectionView) -> Int {
return 1
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.