【问题标题】:How to set number of cells to show in collectionView with RxSwift?如何使用 RxSwift 设置要在 collectionView 中显示的单元格数量?
【发布时间】:2021-06-02 18:52:10
【问题描述】:

我只想在我的 collectionView 中显示 20 个单元格(如果计数少于 20 个,则更少)。我找到了使用委托/数据源的方法,但我的项目完全在 RxSwift/RxCocoa 上,我想找到替代解决方案使用 Rx

如果你知道如何正确使用 Rx,请分享:)

【问题讨论】:

  • 请解释为什么collectionView.rx.items 不适合你。这是显而易见的解决方案。

标签: swift uicollectionview rx-swift


【解决方案1】:

来自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)

单元格配置部分会被自动调用。

【讨论】:

    猜你喜欢
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 2013-11-02
    • 2021-08-24
    • 1970-01-01
    • 2021-06-26
    相关资源
    最近更新 更多