RxSwift를 학습은 했는데, 쓸 때마다 기억이 안난다.
아직 익숙해지지 않아서일까.. 그래서 정리해본다.
어떻게 정리해봐야 할까 고민을 해보아야 할것 같다.
일단 방식만 나열하는 걸로...
총 네가지 방식의 사용법이 존재한다.
1. tableView.rx.items 사용하기
func bindingTableViewItems01() {
let cities = ["01", "L", "K"]
let citiesOb: Observable<[String]> = Observable.of(cities)
citiesOb.bind(to: tableView.rx.items) { (tableView: UITableView, index: Int, element: String) -> UITableViewCell in
guard let cell = tableView.dequeueReusableCell(withIdentifier: TitleCell.identifier) as? TitleCell else {
return UITableViewCell()
}
cell.title?.text = element
// CellType 변경
// element 타입을 기준으로 셀을 리턴 가능
return cell
}
.disposed(by: disposeBag)
}
2. tableView.rx.items(cellIdentifier:String) 사용하기
func bindingTableViewItems02() {
let cities = ["02", "L", "K"]
let citiesOb: Observable<[String]> = Observable.of(cities)
citiesOb.bind(to: tableView.rx.items(cellIdentifier: TitleCell.identifier))
{ (index: Int, element: String, cell: UITableViewCell) in
if let cell = cell as? TitleCell {
cell.title.text = element
}
}
.disposed(by: disposeBag)
}
3. tableView.rx.items(cellIdendifier:String,cellType:Cell.Type) 사용하기
func bindingTableViewItems03() {
let cities = ["03", "L", "K"]
let citiesOb: Observable<[String]> = Observable.of(cities)
citiesOb.bind(to: tableView.rx.items(cellIdentifier: TitleCell.identifier, cellType: TitleCell.self))
{ (index: Int, element: String, cell: TitleCell) in
cell.title.text = element
cell.textLabel?.text = element + " " + element
}
.disposed(by: disposeBag)
}
4. tableView.rx.items(dataSource:protocol<RxTableViewDataSourceType, UITabelViewDataSource>) 사용하기
// tableView를 어떻게 표현할지 미리 지정한 datasource를 사용한 방법
// pod으로 RxDataSource를 설치
// TODO: 참고 자료 https://github.com/RxSwiftCommunity/RxDataSources
func bindingTableViewItems04() {
// RxDataSource에서는 SectionModelType을 따르는 SectionModel을 이미 구현해 놓았는데, 이것을 사용하면 된다.
typealias CitySectionModel = SectionModel<String, String>
typealias CityDataSource = RxTableViewSectionedReloadDataSource<CitySectionModel>
let cities = ["03", "L", "K", "L", "K", "L", "K", "L", "K", "L", "K"]
let sections = [
CitySectionModel(model: "first section", items: cities),
CitySectionModel(model: "second section", items: cities)
]
let configureCell: (TableViewSectionedDataSource<CitySectionModel>, UITableView, IndexPath, String) -> UITableViewCell = {
(datasource, tableView, indexPath, element) in
guard let cell = tableView.dequeueReusableCell(withIdentifier: TitleCell.identifier, for: indexPath) as? TitleCell else {
return UITableViewCell()
}
cell.title.text = element
return cell
}
let datasource = CityDataSource.init(configureCell: configureCell)
datasource.titleForHeaderInSection = { datasource, index in
return datasource.sectionModels[index].model
}
Observable.just(sections)
.bind(to: tableView.rx.items(dataSource: datasource))
.disposed(by: disposeBag)
}