Skip to content

Instantly share code, notes, and snippets.

@vani2
Last active December 30, 2017 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vani2/2de21f4c01b186a93333ad6068b53fa1 to your computer and use it in GitHub Desktop.
Save vani2/2de21f4c01b186a93333ad6068b53fa1 to your computer and use it in GitHub Desktop.
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