Last active
February 8, 2020 00:22
-
-
Save pranjalsatija/4da2737e522d6f27af20da48f2f3dc26 to your computer and use it in GitHub Desktop.
A simple implementation for UITableViewSection.
This file contains 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
class UITableViewSection: NSObject { | |
private(set) var items = [AnyHashable]() | |
private(set) var sectionIndex: Int! | |
private let itemsPublisher: AnyPublisher<[AnyHashable], Never> | |
private let cellProvider: (UITableView, IndexPath, AnyHashable) -> UITableViewCell | |
private var subscriptions = Set<AnyCancellable>() | |
convenience init<T: Hashable>( | |
items: [T], | |
cellProvider: @escaping (UITableView, IndexPath, T) -> UITableViewCell | |
) { | |
self.init( | |
items: Just(items), | |
cellProvider: cellProvider | |
) | |
} | |
init<T: Hashable, P: Publisher>( | |
items: P, | |
cellProvider: @escaping (UITableView, IndexPath, T) -> UITableViewCell | |
) where P.Output == [T], P.Failure == Never { | |
self.itemsPublisher = items.map { $0 as [AnyHashable] }.eraseToAnyPublisher() | |
self.cellProvider = { cellProvider($0, $1, $2 as! T) } | |
} | |
func attach(to descriptor: UITableViewDescriptor, sectionIndex: Int) { | |
self.sectionIndex = sectionIndex | |
itemsPublisher.sink { | |
self.items = $0 | |
descriptor.updateSnapshot() | |
}.store(in: &subscriptions) | |
} | |
} | |
extension UITableViewSection { | |
func cellForRow(in tableView: UITableView, indexPath: IndexPath) -> UITableViewCell { cellProvider(tableView, indexPath, data[indexPath.row]) } | |
func numberOfRows() -> Int { items.count } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment