我有一个动态UITableViewDataSource
,它接受一个Model和一个UITableViewCell
我想在第n行(例如第10行(插入一个不同的UITableViewCell
。。。(用于谷歌广告(
数据源
class ModelTableViewDataSource<Model, Cell: UITableViewCell>: NSObject, UITableViewDataSource {
typealias CellConfigurator = (Model, Cell) -> Void
var models: [Model]
private let reuseIdentifier: String
private let cellConfigurator: CellConfigurator
init(models: [Model], reuseIdentifier: String, cellConfigurator: @escaping CellConfigurator) {
self.models = models
self.reuseIdentifier = reuseIdentifier
self.cellConfigurator = cellConfigurator
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = models[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) as! Cell
cellConfigurator(model, cell)
return cell
}
}
然后我为每个型号添加一个扩展
模型
extension ModelTableViewDataSource where Model == SomeModel, Cell == SomeCell {
static func make(for someModel: [SomeModel], reuseIdentifier: String = "Identifier") -> ModelTableViewDataSource {
return ModelTableViewDataSource(models: someModel, reuseIdentifier: reuseIdentifier) { (someModel, someCell) in
someCell.model = someModel
}
}
}
实现这一点的最佳方法是什么?保持UITableViewDataSource
的可重复使用功能
我想到了这个:
- 创建一个子类
- 重写
numberOfRowsInSection
以返回行数+1 -
超控
cellForRowAt
以处理第10行类ModelTableViewDataSourceWithAd:ModelTableViewDataSource{
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return super.tableView(tableView, numberOfRowsInSection:section) + 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if (indexPath.row == 9) { // return Google ad cell } else { return super.tableView(tableView, cellForRowAt:indexPath) } }
}
然后创建者:
extension ModelTableViewDataSource where Model == SomeModel, Cell == SomeCell {
// ...
static func makeWithAd(for someModel: [SomeModel], reuseIdentifier: String = "Identifier") -> ModelTableViewDataSource {
return ModelTableViewDataSourceWithAd(models: someModel, reuseIdentifier: reuseIdentifier) { (someModel, someCell) in
someCell.model = someModel
}
}
}