(I have already referred this StackOverflow post, however did not find what I was looking for)
I have a requirement to show ads in between cells of a UITableView
.
The image above is used only for representational purposes, and does not show the actual design/data used by the app I am working with.
The normal cells of the UITableView
come from a Core Data
fetch request via NSFetchedResultsController
using fetchController.object(at: indexPath)
, whereas the ad cells come from a different data source altogether.
indexPath
used by NSFetchedResultsController
to retrieve the object from Core Data
fetch request.UITableView
, which can in-turn change the indexPath
of the cells.c
.Please let me know if there is a way to handle all these edge cases efficiently, preferably without changing the indexPath
object used in fetchController.object(at: indexPath)
.
You can add a flag to your table view cell class, telling if to show an ad or not:
class MyTableViewCell: UITableViewCell {
var showAd: Bool = false {
didSet {
// `adView` here being either an IBOutlet from the XIB,
// or a programatically created view, depending on how
// you designed the cell
adView.isHidden = !showAd
}
}
}
With the above in place, what's left is to store an array of randomly generated indices where you want to show the ads, and update the cell accordingly:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = ...
cell.showAd = adIndices.contains(indexPath.row)
return cell
}