我将我的bannerView添加到collectionView标头中。它不允许我将bannerView.rootViewController
设置为headerView的自身,因为它不是UIViewController。
我总是可以在具有collectionView的viewController内实现所需的属性,但是如何加载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())
}
}
包含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
}
}
最佳答案
在headerView
中,我添加了PassthroughView,在cellForItem
中,我将bannerView作为子视图添加到PassthroughView。工作正常
import GoogleMobileAds
class HeaderView: UICollectionReusableView {
var passthroughView: PassthroughView = {
let view = PassthroughView()
view.translatesAutoresizingMaskIntoConstraints = false
view.isUserInteractionEnabled = true
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
// anchors for passthroughView ...
}
func addBannerViewToPassthroughView(_ bannerView: GADBannerView) {
if !bannerView.isDescendant(of: passthroughView) {
passthroughView.addSubview(bannerView)
}
}
}
包含collectionView并提供广告的类位于主vc中,而不是单元中,因此我不必担心单元回收本身并在滚动时不断提供广告:
class MainViewController: UIViewController {
var collectionView: UICollectionView!
var bannerView: GADBannerView!
override func viewDidLoad() {
super.viewDidLoad()
// ... instantiate the collectionView
bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
bannerView.rootViewController = self
bannerView.delegate = self
bannerView.load(GADRequest())
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerView", for: indexPath) as! HeaderView
// for some strange reason adding the bannerView as a subView to the passthroughView inconsistently froze my app (sometimes it did and sometimes it didn't). Once I added it on the mainQueue everything worked fine
DispatchQueue.main.async { [weak self] in
if let bannerView = self?.bannerView {
headerView.addBannerViewToPassthroughView(bannerView)
}
}
return headerView
}
}
请按照this answer获取有关bannerView如何知道何时显示在屏幕上的更多信息。