在TableViewCell里面的UICollectionView没有被调用

我有一个UITableView包含一个水平滚动UICollectionView在这样的每个单元格

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ServiceTypeCell cell.collectionView.delegate = self cell.collectionView.dataSource = self cell.lblName.text = serviceTypes[indexPath.row].name cell.tag = getTag(indexPath) print("uitableviewcell : \(indexPath)") return cell } 

并在每个UICollectionViews

 func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let cell = collectionView.superview?.superview as! ServiceTypeCell let indexPath = getIndexPath(cell.tag) print("uitableviewcell from uicollectionview : \(indexPath)") return serviceTypes[indexPath.row].services.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let tableViewCell = collectionView.superview?.superview as! ServiceTypeCell let tableViewIndexPath = getIndexPath(tableViewCell.tag) let service = serviceTypes[tableViewIndexPath.row].services[indexPath.row] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ServiceTypeDetailCell cell.lblName.text = service.name return cell } 

我的问题是UICollectionView数据源只在UITableViewCell索引0到3之间调用。为什么会发生这种情况?

我的打印debugging结果是这样的

 uitableviewcell : [0, 0] uitableviewcell from uicollectionview : [0, 0] uitableviewcell : [0, 1] uitableviewcell from uicollectionview : [0, 1] uitableviewcell : [0, 2] uitableviewcell from uicollectionview : [0, 2] uitableviewcell : [0, 3] uitableviewcell from uicollectionview : [0, 3] uitableviewcell : [0, 4] uitableviewcell : [0, 5] uitableviewcell : [0, 6] 

不知道,这是否可以解决您的问题,但有消费这么多时间最后我find答案为什么CollectionView的方法不被调用时,它被embedded到TableView中

我们基本上使用这两个:

  • UICollectionViewDataSource

  • UICollectionViewDelegate

但忘了符合这个: UICollectionViewDelegateFlowLayout

符合这个(UICollectionViewDelegateFlowLayout)确实解决了我的问题。

希望它也能解决其他问题。 随意评论和分享您的反馈。 谢谢。

发生这种情况是因为您的集合视图实例与单元格重复使用。 只有4个实例正在创build和重用。

你可以在自定义tableview单元格中编写你的collectionview逻辑,并将自定义单元格作为collectionview的委托和数据源。

在单元类上编写集合视图代码。 并将collectionview委托给cell,因为cell是集合视图的超类。 检查这个屏幕截图 在这里输入图像说明