Skip to content

Instantly share code, notes, and snippets.

@GemmaDelOlmo
Created November 2, 2022 10:43
Show Gist options
  • Select an option

  • Save GemmaDelOlmo/34235057c0a8a2bd31f9d0a38ec34633 to your computer and use it in GitHub Desktop.

Select an option

Save GemmaDelOlmo/34235057c0a8a2bd31f9d0a38ec34633 to your computer and use it in GitHub Desktop.
Strategy Pattern for UITableView with MVP architecture
//STEPS TO IMPLEMENT STRATEGY PATTERN ON PROTOCOL ORIENTED MVP VIEWCONTROLLER WITH MVVM CELLS
//1: The ViewController will have a collection of cell viewModels
//2: There must be a drawer class for each cell that implements the cell drawer protocol
//3: Each of the cellViewModels must implement the viewModel generic protocol in order to have a reference to the cellDrawer
//DRAWER AND VIEWMODEL PROTOCOLS
protocol <#YOUR_DRAWER_PROTOCOL_NAME#> {
func cellFor(tableView: UITableView, atIndexPath: IndexPath) -> UITableViewCell
func draw(_ cell: UITableViewCell, cellViewModel: Any, presenter: <#CONTROLLER_PRESENTER_PROTOCOL#>)
func heightFor(tableView: UITableView, atIndexPath: IndexPath, cellViewModel: Any) -> CGFloat
}
protocol <#YOUR_GENERIC_VIEWMODEL_PROTOCOL_NAME#> {
var cellDrawer: <#YOUR_DRAWER_PROTOCOL_NAME#> {get}
}
//DRAWER FUNCTIONS:
func cellFor(tableView: UITableView, atIndexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(<#YOUR_CELL_CLASS#>, forIndexPath: atIndexPath)
return cell
}
func draw(_ cell: UITableViewCell, cellViewModel: Any, presenter: <#CONTROLLER_PRESENTER_PROTOCOL#>) {
let mycell = cell as! <#YOUR_CELL_CLASS#>
let mycellViewModel = cellViewModel as! <#YOUR_CELL_VIEWMODEL_CLASS#>
mycell.viewModel = mycellViewModel
mycellViewModel.view = mycell
mycell.loadDependingOnViewModel()
}
func heightFor(tableView: UITableView, atIndexPath: IndexPath, cellViewModel: Any) -> CGFloat {
return <#YOUR_CELL_HEIGHT#>
}
//VIEWMODEL VAR
var cellDrawer: <#YOUR_CELL_DRAWER_PROTOCOL#> {
get {
return <#YOUR_CELL_DRAWER_CLASS#>()
}
}
//VIEWCONTROLLER CODE
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = <#YOUR_VIEWMODELS_ARRAY#>[indexPath.row]
let cell = item.cellDrawer.cellFor(tableView: tableView, atIndexPath: indexPath)
item.cellDrawer.draw(cell, cellViewModel: item, presenter: presenter!)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let item = <#YOUR_VIEWMODELS_ARRAY#>[indexPath.row]
return item.cellDrawer.heightFor(tableView: tableView, atIndexPath: indexPath, cellViewModel: item)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment