我有一个嵌入到CollectionView中的TableView,并且我试图在TableView中显示与正确的CollectionViewCell或IndexPath项相对应的相关数据。我尝试这样分配标签: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
}
有什么办法可以解决此问题,或者有其他方法可以实现我想做的事情?感谢您的任何帮助,谢谢!
答案 0 :(得分:0)
嵌套这些实体总是很麻烦,尤其是当您以后需要访问项目的indexPath时。如果正确解决您的问题。我建议的解决方案之一是存储路径的地图(字典)。快速访问它们。这是在类似情况下如何处理此问题的示例:
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)
现在,您可以从外部管理与此嵌套怪物有关的所有数据。