How to get section of UITableView from inside a child UICollectionview

人走茶凉 提交于 2019-12-06 08:09:51
William Hu

You can set the collectionView tag to make it. CollectionView should be the subview of tableViewCell. That is the collectionView can be the property of your customize TableViewCell Seems you are using Prototype Cell.

class YourCustomizeTableViewCell: UITableViewCell {
   let collectionView: CollectionView
   ...
}



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

    let cell = tableView.dequeueReusableCell(withIdentifier: "HorizontalSlideCell", for: indexPath) as! YourCustomizeTableViewCell
   cell.collectionView.tag = indexPath.row

   return cell
}

...

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


//indexPath.section is the collectionview section index but needs to be its parent tableview section's index. How do I get it? 
cellCharLabel?.text = Languages.sharedInstance.alphabets[collectionView.tag].set[indexPath.row].char
 ...
return cell
}

I'm assuming you have a custom UITableViewCell class with an instance of a UICollectionView, so you just need to pass it the section index when you call cellForRowAtIndexPath.

You would need to make a var in the tableViewCell class to hold the section index.

 class CustomTableViewCell: UITableViewCell {
      var sectionIndex:Int?

 }

Then when calling cellForRow... you just pass in the section to that cell.

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "HorizontalSlideCell", for: indexPath) as CustomTableViewCell
    cell.sectionIndex = indexPath.section
    return cell
}

Not sure how you are loading data into the collection views as you aren't showing that but once your table view cell has the section you can then do a number of things to load your data.

Let me know if you need more detail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!