在TableView内部的CollectionView中填充动态数据

问题描述

主视图控制器

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}

func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
    return CategoryNames.count
}

func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell=tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath as IndexPath) as! CategoryTableViewCell
    cell.lblCategoryName.text = CategoryNames[indexPath.row] as? String
    cell.ViewCategogyBackground.layer.cornerRadius=20
    cell.ViewCategogyBackground.layer.maskedCorners = [.layerMaxXMinYCorner]
    
    cell.arrayForCollectionView = [["xx","yy"],["zz","vv","tt"],["hello"],["11","44"]]
    cell.reloadCollectionView()
    return cell
}

表格视图单元格

var arrayForCollectionView : [[String]]!

func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int)       -> Int {
           if (arrayForCollectionView != nil) {
               return arrayForCollectionView.count
           }
           return 0
       }

       func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",for: indexPath) as! CategoryItemCollectionViewCell
             
           

           let rowValue = arrayForCollectionView[indexPath.row]
           for i in 0..<rowValue.count {
               cell.lblItemName.text = rowValue[i] as? String
           }
           return cell
       }

输出 here is my output I want to display data like first section of 2D array under t1(Category 1) and second section under t2(category 2). both categories and items in collection view are dynamic

解决方法

您需要在TableView内部创建CollectionView并在tableViewCell内部创建collectionView的出口,如下所示:

class TimingSlotsTVCell: UITableViewCell
{
    @IBOutlet weak var timeSlotsCV: UICollectionView!
}

现在在tableView的cellForRow中执行以下操作:

let cell = tableView.dequeueReusableCell(withIdentifier: "TimingSlotsTVCell") as! TimingSlotsTVCell
cell.timeSlotsCV.reloadData()
return cell

现在collectionView单元格将从tableView内部调用