Добавление ячеек в Dynami c UITableView DataSource | стриж - PullRequest
1 голос
/ 19 февраля 2020

У меня есть динамический c UITableViewDataSource, который принимает модель, и UITableViewCell

Я хотел бы вставить другой UITableViewCell в строку 'nth' (например, 10-й) ... (для объявлений Google)

DATASOURCE

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

1 Ответ

0 голосов
/ 19 февраля 2020

Я думал об этом:

  • создать подкласс
  • переопределить 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
        }
    }

}
...