Search code examples
iosswiftxcodeuicollectionviewcellxib

Reach CollectionViewCell into Xib with Programatically


I created a Xib File and call in ViewController.Also I create a CollectionView into Xib File.And now I want to reach CollectionViewCell for showing cells.

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!

}

Also I added some code like below . But has no sense!. Where is my mistake?

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
}

}

Solution

  • You did not conform to delegate and dataSource protocols. I think this the problem. Put below lines after collection.register

    collection.delegate = self
    collection.dataSource = self
    

    Hope this will work.