RxSwift용 UITableView와 UICollectionView용 라이브러리
RxDataSource가 없이, RxSwift 와 RxCocoa 만으로 구현할 경우엔 다음과 같이 구현
let data = Observable<[String]>.just(["first element", "second element", "third element"])
data.bind(to: tableView.rx.items(cellIdentifier: "Cell")) { index, model, cell in
cell.textLabel?.text = model
}
.disposed(by: disposeBag)
그러나 여러 Section이 존재할 경우 insert, move, delete시의 애니메이션을 처리할 수 없음
이 때, RxDataSources를 사용하여 처리 가능
Item 구조체
struct BasicData {
let title: String
}
SectionModelType 프로토콜을 채택한 Section 구조체 생성
struct SectionOfBasicData {
var header: String // Section의 헤더
var items: [Item] // Section 내 item의 정보
}
extension SectionOfBasicData: SectionModelType {
typealias Item = BasicData
init(original: SectionOfBasicData, items: [Item]) {
self = original
self.items = items
}
}
dataSource 객체 생성
// 1. Section Data를 생성하기
var sections = BehaviorSubject(value: [
SectionOfBasicData(header: "Basic_First", items: [
BasicData(title: "1111"),
BasicData(title: "2222")
]),
SectionOfBasicData(header: "Basic_Second", items: [
BasicData(title: "3333"),
BasicData(title: "4444")
]),
SectionOfBasicData(header: "Basic_Third", items: [
BasicData(title: "5555"),
BasicData(title: "6666")
]),
])
// 2. 위에서 정의한 section으로 datasource 객체 생성, 이 때 Section 타입을 제네릭으로 넘겨주어야 함
let dataSource = RxTableViewSectionedReloadDataSource<SectionOfBasicData>(configureCell: { dataSource, tableView, indexPath, item -> UITableViewCell in
let cell = tableView.dequeueReusableCell(withIdentifier: "BasicCell", for: indexPath)
cell.textLabel?.text = item.title
return cell
})
// 3. 필요한 경우 header 등 설정 가능
dataSource.titleForHeaderInSection = { dataSource, index in
return dataSource[index].header
}
tableView에 바인딩 시키기
self.sections
.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
RxTableViewSectionedReloadDataSource는 애니메이션 처리를 할 수 없음
애니메이션 처리를 하고 싶다면 RxTableViewSectionedAnimatedDataSource를 사용
| 출처: https://phillip5094.tistory.com/111, https://github.com/RxSwiftCommunity/RxDataSources