Created
February 18, 2016 22:02
-
-
Save JARinteractive/c56e760fa6e0a101e3ee to your computer and use it in GitHub Desktop.
RxSugar TableDelegate for single section table
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
import UIKit | |
import RxSwift | |
import RxSugar | |
protocol GenericTableCell: NSObjectProtocol { | |
typealias Class = Self | |
typealias ValueType | |
func populate(value: ValueType) | |
} | |
class SimpleTable<CellType: GenericTableCell where CellType: UITableViewCell>: NSObject, UITableViewDelegate, UITableViewDataSource { | |
typealias T = CellType.ValueType | |
private let reuseID = "SimpleTableCell" | |
let view = UITableView() | |
let data = Variable<[T]>([T]()) | |
let selection: Observable<T> | |
private let _selection = PublishSubject<T>() | |
init(cellClass: CellType.Type) { | |
selection = _selection.asObservable() | |
super.init() | |
view.delegate = self | |
view.dataSource = self | |
view.registerClass(CellType.self, forCellReuseIdentifier: reuseID) | |
rxs.disposeBag | |
++ data.asObservable().subscribeNext { [weak self] _ in self?.view.reloadData() } | |
} | |
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return data.value.count | |
} | |
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { | |
let cell = tableView.dequeueReusableCellWithIdentifier(reuseID, forIndexPath: indexPath) as! CellType | |
cell.populate(data.value[indexPath.row]) | |
return cell | |
} | |
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { | |
tableView.deselectRowAtIndexPath(indexPath, animated: true) | |
_selection.onNext(data.value[indexPath.row]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment