表格视图单元格Swift iOS内部的嵌套集合视图

时间:2020-01-24 17:31:19

标签: ios uitableview uicollectionview

我正在将collection view嵌套在表格视图单元格内。我需要实现类似于netflix应用商店的屏幕。 您具有诸如 enter image description here

之类的类别

我需要从JSON加载数据,例如-“热门”可能有11个视频,“动作”可能有3个视频,“冒险”可能有20个视频。因此在每个表格视图单元格内,该特定集合视图会加载不同数量的集合视图单元,具体取决于每个类别(“热门”,“动作”,“冒险”)中有多少个视频,这些视频将显示在其各自的水平集合视图中。

到目前为止,我的代码我在表格视图标题中显示每个类别的标题。但是在该类别中,在集合视图 numberOfItemsInSection cellForItemAt 中,我找不到一种相互依赖地加载每个集合视图的方法。例如,与“流行”相关的集合视图1 应加载11个单元格,与“动作”相关的集合视图2 应加载3个单元格。下面是到目前为止的代码

我的视图控件内部的表视图方法

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "categoriesCell") as? CategoriesTableViewCell else { return UITableViewCell() }

    return cell
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    return arrayOfCategoryObjects[section].title
}

func numberOfSections(in tableView: UITableView) -> Int {
    return arrayOfCategoryObjects.count
}

 func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    if let cell = cell as? CategoriesTableViewCell {


        cell.moviesCollectionView.dataSource = self
        cell.moviesCollectionView.delegate = self

        cell.moviesCollectionView.reloadData()

    }
}

我的桌面电脑

class CategoriesTableViewCell: UITableViewCell {

@IBOutlet weak var moviesCollectionView: UICollectionView!

}

我的收藏夹视图代理也位于视图控制器中

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
   // print(arrayOfCategoryObjects[section].movies[section])

    return arrayOfCategoryObjects[section].movies.count

  }

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {


        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "moviesCell", for: indexPath) as! MoviesCollectionViewCell

        cell.movieTitleLbl.text = arrayOfCategoryObjects[indexPath.item].movies[indexPath.item]

        return cell

  }

我的收藏夹视图

class MoviesCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var movieTitleLbl: UILabel!

}

1 个答案:

答案 0 :(得分:2)

您需要为UICollectionView作为父UITableViewCell的{​​{1}}设置标签:

indexPath.section

,然后在您的UICollectionView的委托中:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    if let cell = cell as? CategoriesTableViewCell {

        cell.moviesCollectionView.dataSource = self
        cell.moviesCollectionView.delegate = self
        cell.moviesCollectionView.tag = indexPath.section
        cell.moviesCollectionView.reloadData()

    }
}

希望这会有所帮助!