ios - 获取嵌入到 CollectionView 中的 TableView 中的 IndexPath 项

标签 ios swift uitableview uicollectionview

我有一个嵌入到 CollectionView 中的 TableView,并且我试图在 TableView 中显示与正确的 CollectionViewCell 或 IndexPath Item 相对应的相关数据。我尝试这样分配标签: cell.tableView.tag = indexPath.item 但它似乎有问题。

我在我的collectionViewCell中尝试了print(tableView.tag)并且它打印了 2 1 0 3 4 5 但我总共有 7 个 collectionViewCells,因此最后一个标签由于某种原因没有打印。

我的collectionView已经嵌入到另一个TableView中,下面是MasterTableViewCell.swift中的代码:

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


        if diningIndexPath.section == 0 {
            let cell: FoodCourtCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "foodCourtCell", for: indexPath) as! FoodCourtCollectionViewCell

            cell.tableView?.register(UINib(nibName: "RestaurantTableViewCell", bundle: nil), forCellReuseIdentifier: "restaurantCell")


            cell.tableView.tag = indexPath.item

            //...

            return cell
      }
}

在 customCollectionViewCell.swift 中,我的 tableView 有以下代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: RestaurantTableViewCell = tableView.dequeueReusableCell(withIdentifier: "restaurantCell", for: indexPath) as! RestaurantTableViewCell

        print(tableView.tag)

        let currentRestaurant = foodCourts[tableView.tag].childLocations[indexPath.row]
        cell.textLabel.text = currentRestaurant.name

        //...

        return cell
    }

有什么方法可以解决这个问题,或者有其他方法可以实现我想要做的事情吗?感谢任何帮助,谢谢!

最佳答案

嵌套这些实体总是很痛苦,尤其是当您稍后需要访问项目的索引路径时。如果正确理解你的问题。我建议的解决方案之一是存储路径的 map (字典)。为了快速访问它们。以下是我在类似情况下如何处理此问题的示例:

typealias CollectionIndexPath = IndexPath
typealias TableIndexPath = IndexPath
var indexMap: [CollectionIndexPath: TableIndexPath] = [:]

现在当您需要访问某些项目或配置它时。

func cellForItemAtIndexPath { ... } {
     let cell = { ... }

     let cellPath = indexPath
     let tablePath = indexMap[cellPath]
     let foodCourtForCell = foodCourts[cellPath.item]
     let childLocationsForTableView = foodCourtForCell.childLocations

     cell.configureWith(court: foodCourtForCell, locations: childLocations)

现在您可以从外部管理与该嵌套怪物相关的所有数据。

关于ios - 获取嵌入到 CollectionView 中的 TableView 中的 IndexPath 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52188907/

相关文章:

html - 链接到页面的特定部分

ios - Firebase 不显示通知

swift - 快速错误当我删除一行时,它崩溃了

ios - 如何使用分段控件在一个 TableView 中维护两个自定义单元格?

ios - RestKit POSTing multipartFormRequest 与字典参数会在数据中添加反斜杠

ios - 纯代码构建集合但不执行 UICollectionViewDelegateFlowLayout

swift - NSURLConnection 此服务器的证书无效

ios - Main.storyboard 和 ViewController.swift 如何绑定(bind)到一个空的 iOS 项目中?

iphone - iPhone 上表格 View 中单元格的奇怪行为,如果一个单元格导致另一个单元格发生变化,则会发生变化

ios - 使用数组在 UITableView 中具有不同标签颜色的不同单元格