SimpleDataSource
Simplifies data source implementation by reorganising responsibilities and using a data driven approach. Improves reusability and decreases the amount of boilerplate.
Usage
Note: For simplicity I'll be addressing UITableView only, but everything, including framework support, extends to UICollectionView
Responsibility reorganisation starts with moving the view model presentation to the cell.
Next, specify the cell type that should be registered and dequeued for a particular view model. To be able to use the default implementations, TableViewCell.ViewModel
must equal Self
.
Instead of implementing a custom UITableViewDataSource
, we will use SimpleTableViewDataSource
. We simply initialise and set it as the tableViews dataSource.
Finally, map and present the data. For the view model mapping we can use the tableViewPresentable
computed property.
That's it! Check it out by running the demo project.
For a more detailed showcase, take a look at this blog post.
Installation
Carthage
github "Rep2/ReusableDataSource" ~> 0.3
Detailed overview
DequeuableTableViewCellViewModel
protocol specifies how to register and dequeue a table view cell from a view model.
PresentingCollectionViewCell
protocol defines a view model type that a cell can present. It also specifies the cell source which is used during the cell registration.
By combining the previously defined associated types, we can provide default implementations for cell registration and dequeue, as long as TableViewCell
is UITableViewCell
, and TableViewCell.ViewModel
equals view model type that implemented the DequeuableTableViewCellViewModel
protocol.
As the DequeuableTableViewCellViewModel
contains an associated type, we can only use it as a generic constraint. To be able to pass it as a parameter, we need to remove the associated type using type-erasure. This is the role of AnyDequeuableTableViewCellViewModel
.
tableViewPresentable
is a stored property of DequeuableTableViewCellViewModel
that simplifes this transformation.
SimpleTableViewDataSource
implements the UITableViewDataSource
by using the register and dequeue closures.
By default SimpleTableViewDataSource
registers a cell each time it's presented. This means that the number of cell registrations is the same as the number of cell presentations. To remove this behavior set the automaticallyRegisterReuseIdentifiers
to false.