Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RMR Table Presentation Model Example
// Базовый класс, используется для нетабличных экранов
class PresentationModel {
}
typealias ListViewModel = Any
typealias CellMapper = (ListViewModel.Type) -> ListCell.Type
// Класс табличной ячейки
class ListCell: UITableViewCell { func configure(for viewModel: Any) {} }
// Секция таблицы
struct TableSection {
let title: ListViewModel
let items: [ListViewModel]
}
// Класс табличного экрана
class TablePresentationModel: PresentationModel, UITableViewDataSource {
var sections = [TableSection]()
var cellMapper: CellMapper { preconditionFailure() }
init(viewModelTypes: [ListViewModel.Type]) {
self.listViewModelClasses = viewModelTypes
super.init()
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let viewModel = sections[indexPath.section].items[indexPath.row]
let viewModelType = type(of: viewModel)
let cellIdentifier = String(describing: cellMapper(viewModelType.self))
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? ListCell else { preconditionFailure() }
cell.configure(for: viewModel)
return cell
}
}
// Базовый класс для view controller
class ViewController: UIViewController<PM: PresentationModel> {
let presentationModel: PM
}
// Класс view controller с таблицей
final class ConcreteViewController: ViewController<ConcreteTablePresentationModel>, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = presentationModel
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment