Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用RxSwift设置要在collectionView中显示的单元格数?_Swift_Uicollectionview_Rx Swift - Fatal编程技术网

如何使用RxSwift设置要在collectionView中显示的单元格数?

如何使用RxSwift设置要在collectionView中显示的单元格数?,swift,uicollectionview,rx-swift,Swift,Uicollectionview,Rx Swift,我只想在我的集合视图中显示20个单元格(如果计数小于20,则显示更少)。我找到了使用代理/数据源的方法,但我的项目完全基于RxSwift/RxCocoa,我想找到另一种解决方案,使用Rx 如果您知道如何正确使用Rx,请分享:)的示例代码 简单的情况是,collectionView的数据源是静态的 // In RxSwift, cell's count = dataSource.elementArray.count let dataSource = Observable

我只想在我的集合视图中显示20个单元格(如果计数小于20,则显示更少)。我找到了使用代理/数据源的方法,但我的项目完全基于RxSwift/RxCocoa,我想找到另一种解决方案,使用Rx

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

的示例代码

简单的情况是,
collectionView
的数据源是静态的

       // 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)

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

请解释为什么
collectionView.rx.items
不适用于您。这是显而易见的解决办法。
// equals to collectionView.reloadData
dataSource.onNext(newArr)