Created
May 18, 2018 11:10
-
-
Save mokagio/56a67b2285b2ddf5f3511cfb077cd415 to your computer and use it in GitHub Desktop.
Ready made `UITableViewDataSource` for those simple scenarios in which you want to display homogeneous data, of type `T`, in a single section, on a standard `UITableViewCell`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// swift version 4.1 | |
import UIKit | |
/// Ready made `UITableViewDataSource` for those simple scenarios in which you want to display | |
/// homogeneous data, of type `T`, in a single section, on a standard `UITableViewCell`. | |
class SimpleDataSource<T>: NSObject, UITableViewDataSource { | |
typealias Item = T | |
let data: [T] | |
let configure: (UITableViewCell, T) -> UITableViewCell | |
let identifier = "simple-data-source-cell" | |
init(tableView: UITableView, data: [T], configure: @escaping (UITableViewCell, T) -> UITableViewCell) { | |
self.data = data | |
self.configure = configure | |
super.init() | |
tableView.dataSource = self | |
tableView.register(UITableViewCell.self, forCellReuseIdentifier: identifier) | |
} | |
func item(for indexPath: IndexPath) -> T? { | |
guard indexPath.row < data.count else { return .none } | |
return data[indexPath.row] | |
} | |
// MARK: - UITableViewDataSource | |
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return data.count | |
} | |
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) | |
guard let item = item(for: indexPath) else { return cell } | |
return configure(cell, item) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My app has outgrown this very simple component, but I thought it'd be useful to dump it here for future use. I mean... is not rocket science, but will save some typing 😉 .