表格视图内的集合视图

时间:2019-05-29 07:43:04

标签: swift

我有以下问题。 在我的项目中,我有一个包含多个部分的表格视图,每个部分一行。在行内,我有一个收藏视图。 集合视图项的计数取决于集合所在的部分。但是,当我为集合视图调用func numberOfItemsInSection时,我不明白如何访问部分号。

这是我的代码:

ViewController.swift

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

TableCell.swift

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    //TODO ?????? How can i get here section of table view
}

谢谢!

2 个答案:

答案 0 :(得分:0)

在UITableViewCell子类中创建一个数组,并在collectionview数据源方法中使用该数组

class CustomCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    var collectionData = [String]()

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return collectionData.count
    }
}

tableView cellForRowAt方法中,将值分配给数组并重新加载Colletion视图

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as? CustomCell
    cell?.collectionData = []//assign data here based on indexPath.section
    cell?.collectionView.reloadData()
    return cell!
}

答案 1 :(得分:0)

您可以在此处使用面向对象的方法,在表格单元格中创建变量tableSectionNumber。喜欢

class YourCell: UITableViewCell {
    public var tableViewSectionNumber: Int = 0;
....

现在在collectionView numberOfItemsInSection方法中,您可以访问它

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//TODO ?????? How can i get here section of table view
  self.tableViewSectionNumber // its here
 }

现在,当您在TableView cellForRowItem方法(如Like)中填充单元格时,可以在ViewController的单元格中设置此值。

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

    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! YourCell
    cell.tableViewSectionNumber = indexPath.section // here you set the section number in cell
}
相关问题