我创建了一个Xib文件并在ViewController中调用。我还创建了一个CollectionView到Xib文件中。现在我想到达CollectionViewCell来显示单元格。
class ProductVC: UIViewController {
var collection:UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
let productView : ProductDetailView = UIView.fromNib()
productView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(productView)
collection = productView.collectionView
collection.register(UINib(nibName: "TagCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "TagCollectionViewCell")
productView.topAnchor.constraint(equalTo: view.safeTopAnchor).isActive = true
productView.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width).isActive = true
productView.heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.height).isActive = true
}
}
class ProductDetailView: UIView {
@IBOutlet var productTitle: UILabel!
@IBOutlet var dateLabel: UILabel!
@IBOutlet var productImage: UIImageView!
@IBOutlet var productDescriptionLabel: UILabel!
@IBOutlet var collectionView: UICollectionView!
}
class TagCollectionViewCell: UICollectionViewCell {
@IBOutlet var tagName: UILabel!
}
我还添加了以下代码。但是没有任何意义!我的错误在哪里?
extension ProductVC : UICollectionViewDelegate , UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell: TagCollectionViewCell! = collectionView.dequeueReusableCell(withReuseIdentifier: "TagCollectionViewCell", for: indexPath) as? TagCollectionViewCell
if cell == nil {
collectionView.register(UINib(nibName: "TagCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "TagCollectionViewCell")
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TagCollectionViewCell", for: indexPath) as? TagCollectionViewCell
}
cell.tagName.text = "aa"
return cell
}
}
答案 0 :(得分:1)
您不符合委托和dataSource协议。我认为这是问题所在。在 collection.register
之后的下面几行collection.delegate = self
collection.dataSource = self
希望这会起作用。