以编程方式将 UICollectionViewCell 设置为 Xib 宽度

Reach CollectionViewCell into Xib with Programatically

我创建了一个 Xib 文件并调用 ViewController.Also 我在 Xib 中创建了一个 CollectionView File.And 现在我想访问 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
}

}

您没有遵守委托和数据源协议。我认为这是问题所在。在 collection.register

之后放在下面几行
collection.delegate = self
collection.dataSource = self

希望这会奏效。