Search code examples
iosswiftxcodeuitableviewxib

Swift Reload CollectionView in Tableview Header with Xib


I try to implement detail view about a product. I use tableview for product details and I decide to create a collectionview for product images in the tableview header. I create a Xib file that includes a collection view and 2 labels. And I implemented this Xib to tableview header. I can reload the tableview rows but I didnt reload the collectionview in header.

How can I reload this collectionview?

I use this code after pulling json and it allows me show the paramters in tableview cells.

let sectionIndex = IndexSet(integer: 0)
self.tableView.reloadSections(sectionIndex, with: .none)

In viewDidLoad()

if element.result.productImages?.count ?? 0 > 0 {
    for x in element.result.productImages! {
        print(x)
        self.productImages.append(x.imageUrl)
        self.productDetailHeaderView.productImagesCollectionView.reloadData()
    }
}

In CellForRowAt

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProductImagesCollectionViewCell", for: indexPath) as! ProductImagesCollectionViewCell
    cell.productImage.sd_setImage(with: URL(string: "\(productImages[indexPath.row])"), placeholderImage: UIImage(named: "placeholder"))
    return cell
}

--

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let v : ProductDetailHeaderView = UIView.fromNib()
    productDetailHeaderView = v
    productDetailHeaderView.translatesAutoresizingMaskIntoConstraints = false

    productDetailHeaderView. productImagesCollectionView.register(UINib(nibName: "ProductImagesCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "ProductImagesCollectionViewCell")

    productDetailHeaderView.backgroundColor = .yellow


    return productDetailHeaderView
}

Thanks in advance.


Solution

  • You may need to set the delegate and dataSource

    productDetailHeaderView.productImagesCollectionView.register(UINib(nibName: "ProductImagesCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "ProductImagesCollectionViewCell")  
    productDetailHeaderView.productImagesCollectionView.delegate = self 
    productDetailHeaderView.productImagesCollectionView.dataSource = self