应用程序方案
正如你从方案中看到的那样,我有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()
中的UITableView
的reloadData()
我认为问题在于单元格是可重用的,这就是为什么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
}