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

AdMob报错无效帧尺寸:设置宽高后仍无法加载广告

解决AdMob Banner广告因宽高(0,0)无法加载的问题
  • 检查自定义BannerAd视图的内部实现
    你在外层给BannerAd添加了frame,但如果内部的GADBannerView没有正确绑定父视图尺寸,还是会出现宽高为0的错误。需要确保自定义View中,AdMob的广告视图能跟随外层布局的尺寸:
struct BannerAd: UIViewRepresentable {
    let unitID: String
    
    func makeUIView(context: Context) -> GADBannerView {
        let bannerView = GADBannerView(adSize: GADAdSizeBanner)
        bannerView.adUnitID = unitID
        bannerView.rootViewController = UIApplication.shared.windows.first?.rootViewController
        return bannerView
    }
    
    func updateUIView(_ uiView: GADBannerView, context: Context) {
        // 让广告视图尺寸跟随父视图边界
        uiView.frame = uiView.superview?.bounds ?? CGRect(x: 0, y: 0, width: 320, height: 50)
        uiView.load(GADRequest())
    }
}
  • 改用AdMob自适应广告尺寸
    固定宽高可能在多设备适配中出问题,用官方推荐的自适应尺寸让AdMob自动匹配合适的广告规格,避免手动设置的误差:
func makeUIView(context: Context) -> GADBannerView {
    // 根据屏幕宽度生成自适应尺寸
    let adaptiveSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(UIScreen.main.bounds.width)
    let bannerView = GADBannerView(adSize: adaptiveSize)
    bannerView.adUnitID = unitID
    bannerView.rootViewController = UIApplication.shared.windows.first?.rootViewController
    bannerView.load(GADRequest())
    return bannerView
}

这种情况下外层无需手动设置frame,或仅给父容器设置宽度约束即可。

  • 确保父视图布局有明确约束
    你当前的HStack搭配Spacer的布局,要确保父视图有明确的尺寸限制(比如不能放在无高度约束的ScrollView中)。可以给HStack添加高度约束,保证子视图能获取到有效尺寸:
HStack {
    Spacer()
    BannerAd(unitID: "ca-app-pub ...")
    Spacer()
}
.frame(height: 50)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 08:10:29