Swift CollectionView中AdMob单元格遮挡帖子问题求助
解决CollectionView插入广告遮挡帖子的问题
问题根源
你的代码直接用indexPath.row取newsData的数据,但插入广告后,CollectionView总项数多于帖子数,且广告占用了原本属于帖子的位置,导致后续帖子的索引对应错误,最终出现帖子被遮挡、消失的情况。
解决步骤
1. 修正总项数计算
先在numberOfItemsInSection方法中返回正确的总项数:帖子数量加上需插入的广告数(每4篇帖子插1个广告)。
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let postCount = newsData.count let adCount = postCount / 4 return postCount + adCount }
2. 修正cellForItemAt的索引逻辑
需要判断当前位置是广告位还是帖子位,并计算帖子在newsData中的正确索引:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 判断当前是否为广告位:每4篇帖子后插入广告(0-based索引对应4、9、14...) if (indexPath.item + 1) % 5 == 0 { let adcell = collectionView.dequeueReusableCell(withReuseIdentifier: "adcell", for: indexPath) as! MovieCollectionViewCell // 加载Google Ads的逻辑 return adcell } else { // 计算帖子在newsData中的真实索引:减去当前位置之前已插入的广告数量 let postIndex = indexPath.item - (indexPath.item / 5) let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MovieCollectionViewCell", for: indexPath) as! MovieCollectionViewCell cell.setup(with: newsData[postIndex]) return cell } }
逻辑说明
- 广告位判断:
(indexPath.item + 1) % 5 == 0确保每4篇帖子后(第5个位置)插入广告,0-based索引对应4、9、14... - 帖子索引计算:
indexPath.item / 5会得到当前位置之前已插入的广告数量,用当前位置减去这个数量,就能得到newsData中对应的帖子索引,避免广告占用位置导致的索引偏移。
比如你的5篇帖子案例:总项数为5+1=6,位置0-3展示帖子0-3,位置4展示广告,位置5展示帖子4,不会出现帖子消失的情况。
内容的提问来源于stack exchange,提问作者noorapps
相关产品推荐
相关产品推荐

