I'm adding my bannerView inside a collectionView header. It won't let me set the bannerView.rootViewController as self to the headerView because it's not a UIViewController.
I can always implement the required properties inside the viewController that has the collectionView but then how do I load the bannerView?
class HeaderView: UICollectionReusableView {
var bannerView: GADBannerView = {
let view = GADBannerView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
bannerView.rootViewController = self
bannerView.load(GADRequest())
}
}
class that contains the collectionView:
class MainViewController: UIViewController {
var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// ... instantiate the collectionView
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerView", for: indexPath) as! HeaderView
return headerView
}
}

Inside the
headerViewI added a PassthroughView and insidecellForItemI added the bannerView as subView to the PassthroughView. It works fineThe class that contains the collectionView and serves the ads are in the main vc and NOT the cell so I don't have to worry about the cell recycling itself and constantly serving ads as it's scrolled:
Follow this answer for more info on how the bannerView knows when it is and isn't on screen.