来自RxSwift的示例代码
简单的情况是collectionView的dataSource是静态的
// In RxSwift, cell's count = dataSource.elementArray.count
let dataSource = Observable.just([
1,
2,
3
])
dataSource.bind(to: collectionView.rx.items) { (collectionView, row, element) in
// cell configuration part
let indexPath = IndexPath(row: row, section: 0)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! NumberCell
cell.value?.text = "\(element) @ \(row)"
return cell
}
.disposed(by: disposeBag)
一般用途:
collectionView的数据源是可变的,并且有默认数据,
使用BehaviorSubject
// change the arr to the array of the model you want
let arr = [ 1,
2,
3
]
// change the type of [Int] to the type of [the model you want]
// In RxSwift, cell's count = dataSource.elementArray.count
lazy var dataSource = BehaviorSubject<[Int]>(value: arr)
dataSource.bind(to: collectionView.rx.items) { (collectionView, row, element) in
// cell configuration part
// the same as above
let indexPath = IndexPath(row: row, section: 0)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! NumberCell
cell.value?.text = "\(element) @ \(row)"
return cell
}
.disposed(by: disposeBag)
如果数据源不同,
// equals to collectionView.reloadData
dataSource.onNext(newArr)
单元格配置部分会被自动调用。