You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在无限滚动UICollectionView中每9个单元格展示不同Admob横幅广告?

实现每第9个单元格展示不同AdMob广告的方案

首先要纠正一个误区:你不需要手动创建多个adUnitID来展示不同的广告。AdMob的广告投放系统本身就会为同一个adUnitID自动返回不同的广告创意,你当前看到重复广告大概率是因为使用了测试adUnitID(比如你代码里的ca-app-pub-3940256099942544/2934735716),测试ID只会返回固定的测试广告,换成正式adUnitID后就会自动展示不同的广告内容。

不过如果你确实需要使用多个adUnitID(比如用于区分不同位置的广告效果统计),也可以轻松实现循环切换,下面是具体方案:


步骤1:准备多个adUnitID列表

在你的ViewController类里定义一个存储正式adUnitID的数组(需要先在AdMob后台创建这些ID):

// 替换成你在AdMob后台创建的正式adUnitID
private let adUnitIDs = [
    "ca-app-pub-xxxxxx/xxxx1",
    "ca-app-pub-xxxxxx/xxxx2",
    "ca-app-pub-xxxxxx/xxxx3"
]

步骤2:修改cellForItemAt逻辑

计算当前是第几个广告单元格,然后循环使用adUnitID数组里的ID,同时优化单元格复用逻辑(避免重复添加BannerView):

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    if indexPath.item % 9 == 0 { 
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: adCellId, for: indexPath) as! AdCell 
        
        // 计算当前是第几个广告单元格(比如indexPath.item=0是第0个,9是第1个,以此类推)
        let adSequenceIndex = indexPath.item / 9
        // 循环选取adUnitID数组里的ID
        let targetAdUnitID = adUnitIDs[adSequenceIndex % adUnitIDs.count]
        
        let adSize = GADAdSizeFromCGSize(CGSize(width: self.view.frame.width, height: adViewHeight)) 
        // 先移除cell中已有的BannerView,避免复用重复添加
        cell.contentView.subviews.forEach { $0.removeFromSuperview() }
        
        let bannerView = GADBannerView(adSize: adSize) 
        bannerView.adUnitID = targetAdUnitID 
        bannerView.delegate = self 
        bannerView.rootViewController = self 
        bannerView.translatesAutoresizingMaskIntoConstraints = false 
        
        cell.contentView.addSubview(bannerView) 
        // 添加约束确保BannerView铺满单元格
        NSLayoutConstraint.activate([
            bannerView.topAnchor.constraint(equalTo: cell.contentView.topAnchor),
            bannerView.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor),
            bannerView.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor),
            bannerView.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor)
        ])
        
        let request = GADRequest() 
        bannerView.load(request) 
        return cell 
    } else { 
        // 普通内容单元格的逻辑
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "normalCellId", for: indexPath) as! NormalCell
        // 配置普通单元格内容...
        return cell
    } 
}

额外优化建议

  1. 复用BannerView:最好在AdCell类里提前初始化好GADBannerView,而不是每次都创建新的,复用的时候只更新adUnitID和加载请求,这样能提升滚动性能。
  2. 测试广告注意:测试阶段用测试ID时,重复广告是正常现象,上线前替换成正式ID即可看到不同的广告。
  3. 广告加载失败处理:实现GADBannerViewDelegate的adViewDidFailToReceiveAdWithError方法,处理广告加载失败的情况,比如隐藏广告单元格或显示占位内容。

内容的提问来源于stack exchange,提问作者Kirill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:36:27