iOS UICollectionView Example
FuseAdView
objects can be used inside an UICollectionViewCell
in the same way as other UIView
objects.
Make sure you hold on to the banner view objects once created, as re-creating them will reload the banner (triggering a new banner ad request to the server).
For example:
Collection Cell
class FuseCell: UICollectionViewCell {
static let reuseIdentifier = "FuseCell"
var adView: FuseAdView? {
didSet {
configureAdView()
}
}
func configureAdView() {
if let adView {
// Add to cell content view.
contentView.addSubview(adView)
// Apply layout constraints.
NSLayoutConstraints.activate([
adView.topAnchor.constraint(equalTo: contentView.topAnchor),
adView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
adView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
adView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
])
}
}
func prepareForReuse() {
super.prepareForReuse()
adView.removeFromSuperview()
adView = nil
}
}
View Controller
class MyCollectionViewController: UICollectionViewController {
var adViews = [IndexPath: FuseAdView]()
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
...
if (isBannerCell) {
var cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FuseCell", for: indexPath) as? FuseCell
let adView = fuseAdView(for: indexPath)
cell?.adView = adView
return cell
} else {
...
}
}
// Retrieve banner ad view for this cell.
func fuseAdView(for: IndexPath) -> FuseAdView {
if let adView = adViews[indexPath] {
return adView
}
let adView = FuseAdView("banner")
adViews[indexPath] = adView
return adView
}
}