如何在UICollectionViewCell类中获取UITableView当前项索引



应用程序方案

正如你从方案中看到的那样,我有UITableView,在UITableViewCells中有UICollectionView。我面临的问题是,当我在UICollectionView中的标签上设置文本时,我无法获得正确的UITableViewCell编号

以下是我如何检查UITableView当前的哪一行:

extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ExploreTableViewCell

cell.currentTableViewRow = indexPath.item

return cell
}

}

然后我根据我创建的currentTableViewRow变量设置标签值:

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

switch(currentTableViewRow) {

case 1:

cell.collectionTitle.text = Const.newCollection.subCollections[indexPath.item]

case 2:

cell.collectionTitle.text = Const.freeCollection.subCollections[indexPath.item]

case 3:

cell.collectionTitle.text = Const.mostLikedCollection.subCollections[indexPath.item]

case 4:

cell.collectionTitle.text = Const.healthFitnessCollection.subCollections[indexPath.item]

case 5:

cell.collectionTitle.text = Const.earthCollection.subCollections[indexPath.item]

default:

cell.collectionTitle.text = Const.autumnEditionCollection.subCollections[indexPath.item]

}

return cell
}

此外,我的viewDidAppear()中的UITableViewreloadData()

我认为问题在于单元格是可重用的,这就是为什么UITableView的前4行是正确的,而其他行则不是。有什么建议吗?

UITableViewCell:中添加函数

func reloadCollectionView() -> Void {
self.collectionView.reloadData()
}

然后像这样使用:

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

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ExploreTableViewCell

cell.currentTableViewRow = indexPath.item
cell.reloadCollectionView()

return cell
}

最新更新