我有一个嵌入到 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/