Swift 使用 Xib 在 Tableview Header 中重新加载 CollectionView

Swift Reload CollectionView in Tableview Header with Xib

我尝试实现有关产品的详细视图。我使用表视图查看产品详细信息,我决定在表视图 header 中为产品图片创建一个 collection 视图。我创建了一个包含 collection 视图和 2 个标签的 Xib 文件。我将这个 Xib 实现到 tableview header。我可以重新加载表格视图行,但我没有在 header 中重新加载 collection 视图。

如何重新加载此 collection 视图?

我在拉取 json 后使用此代码,它允许我在表格视图单元格中显示参数。

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

在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()
    }
}

在 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
}

提前致谢。

您可能需要设置委托和数据源

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