如何在Swift应用内容中间插入AdMob自适应横幅广告?
在Swift App内容中间插入AdMob自适应横幅广告的解决方案
你之前尝试直接拼接字符串和广告是行不通的——因为GADBannerView是UI组件,不是文本内容,没法和字符串直接相加。下面是两种可行的实现方案:
方案1:使用UITableView(适合长内容)
把内容拆分成「文本块-广告-文本块」三个部分,用TableView的不同cell来承载:
步骤1:定义Cell类型
先创建两个自定义Cell:
// 显示文本的Cell class TextContentCell: UITableViewCell { let contentLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.translatesAutoresizingMaskIntoConstraints = false return label }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(contentLabel) NSLayoutConstraint.activate([ contentLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 16), contentLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), contentLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), contentLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -16) ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // 显示广告的Cell class AdBannerCell: UITableViewCell { var bannerView: GADBannerView! override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupBannerView() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupBannerView() { let adWidth = UIScreen.main.bounds.width - 32 // 左右留边 let adSize = GADCurrentOrientationInlineAdaptiveBannerAdSizeWithWidth(adWidth) bannerView = GADBannerView(adSize: adSize) bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716" bannerView.rootViewController = self.window?.rootViewController bannerView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(bannerView) NSLayoutConstraint.activate([ bannerView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 16), bannerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), bannerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), bannerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -16) ]) // 加载广告 bannerView.load(GADRequest()) } }
步骤2:分割内容并配置TableView
在你的ViewController里:
class ContentViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { let tableView = UITableView() var firstHalfText = "" var secondHalfText = "" override func viewDidLoad() { super.viewDidLoad() setupTableView() splitContent() } private func splitContent() { let cont = "This is my content here" // 实际替换为WordPress接口返回的内容 let words = cont.components(separatedBy: " ") guard !words.isEmpty else { return } let halfLength = words.count / 2 firstHalfText = words[0..<halfLength].joined(separator: " ") secondHalfText = words[halfLength..<words.count].joined(separator: " ") } private func setupTableView() { tableView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(tableView) NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor), tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) ]) tableView.register(TextContentCell.self, forCellReuseIdentifier: "TextCell") tableView.register(AdBannerCell.self, forCellReuseIdentifier: "AdCell") tableView.dataSource = self tableView.delegate = self } // MARK: - TableView DataSource func numberOfSections(in tableView: UITableView) -> Int { return 3 // 文本块1、广告、文本块2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: let cell = tableView.dequeueReusableCell(withIdentifier: "TextCell", for: indexPath) as! TextContentCell cell.contentLabel.text = firstHalfText return cell case 1: let cell = tableView.dequeueReusableCell(withIdentifier: "AdCell", for: indexPath) as! AdBannerCell return cell case 2: let cell = tableView.dequeueReusableCell(withIdentifier: "TextCell", for: indexPath) as! TextContentCell cell.contentLabel.text = secondHalfText return cell default: return UITableViewCell() } } }
方案2:使用UIStackView(适合短内容)
如果内容不长,直接用StackView把文本标签和广告视图按顺序排列:
class ContentViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() setupContentAndAd() } private func setupContentAndAd() { // 1. 分割内容 let cont = "This is my content here" let words = cont.components(separatedBy: " ") guard !words.isEmpty else { return } let halfLength = words.count / 2 let firstHalf = words[0..<halfLength].joined(separator: " ") let secondHalf = words[halfLength..<words.count].joined(separator: " ") // 2. 创建文本标签 let firstLabel = UILabel() firstLabel.text = firstHalf firstLabel.numberOfLines = 0 let secondLabel = UILabel() secondLabel.text = secondHalf secondLabel.numberOfLines = 0 // 3. 创建广告视图 let adWidth = UIScreen.main.bounds.width - 32 let adSize = GADCurrentOrientationInlineAdaptiveBannerAdSizeWithWidth(adWidth) let bannerView = GADBannerView(adSize: adSize) bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716" bannerView.rootViewController = self bannerView.load(GADRequest()) // 4. 用StackView组合 let stackView = UIStackView(arrangedSubviews: [firstLabel, bannerView, secondLabel]) stackView.axis = .vertical stackView.spacing = 16 stackView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(stackView) NSLayoutConstraint.activate([ stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16), stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16), stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16) ]) } }
注意事项
- 自适应横幅的宽度要根据实际布局设置(比如去掉左右内边距后的宽度),不要固定320,适配不同屏幕。
- 可以监听
GADBannerViewDelegate的bannerViewDidReceiveAd(_:)和bannerView(_:didFailToReceiveAdWithError:)方法,处理广告加载成功/失败的布局调整。 - 测试时用AdMob提供的测试ID,上线前替换为正式ID。
内容的提问来源于stack exchange,提问作者noorapps
相关产品推荐
相关产品推荐

