无法使用 RxSwift 变量 asObservable() 设置绑定(到:UITableView)

Posted

技术标签:

【中文标题】无法使用 RxSwift 变量 asObservable() 设置绑定(到:UITableView)【英文标题】:Cannot set bind(to: UITableView) with RxSwift Variable asObservable() 【发布时间】:2017-09-09 12:05:44 【问题描述】:

我正在尝试绑定(到:) 一个 collectionView,但 tableView 也不起作用。我有一个 viewModel,我的 Variable 在哪里,我想在值更改时使用我的 tableView 进行订阅。

viewModel.theVariable
        .asObservable()
        .bind(to: tableView.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self))
            (row, item, cell) in
            cell.textLabel?.text = item
        
        .addDisposableTo(disposeBag)

XCode 告诉我 Type 'inout UITableView' does not conform to protocol 'ReactiveCompatible' 这应该是因为它适用于任何 UIView。

我已经用它的 just() 尝试了 Observable,而且这种方法似乎工作正常。问题是我需要有一个变量,我在 viewModel 和视图中设置了一个值,我需要观察这个变化。不确定 Observable 是否提供此方法。

关键是即使使用变量,这也应该工作?它是一个错误吗?我正在使用 Swift 3.2

【问题讨论】:

你的变量是什么类型的? 我创建的自定义模型... 自定义数组对吗? 没错,我有一个模型,其中包含 Array、Int 和 Int。这就是变量正在观察的内容 我正在制作一个游乐场示例 【参考方案1】:

这是一个工作代码示例:

    var dataSource : PublishSubject<[String]> = PublishSubject()

    dataSource.asObservable().bind(to: self.mProductsCollectionView.rx.items)  (collectionView, row, element ) in
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "reuseIdentifier", for: IndexPath(row : row, section : 0))
        //customize cell
        return cell

    .addDisposableTo(bag)

    publish.onNext(["blah", "blah", "blah"])

【讨论】:

我将在今天晚些时候尝试这个,如果这是正确的,那么赏金就是你的 :) 有机会试试吗? 好的,所以问题似乎是我正在使用我自己的模型,其中包含一个数组。好像我需要立即使用数组。所以我将数组映射为 bind(to:) 函数的输入,它似乎可以工作。也许它甚至可以与变量一起使用。谢谢你,赏金是你的......【参考方案2】:

这是 Swift 3 中的工作代码

 var countries = Variable([Country]())
 countries.asObservable()
  .bind(to: tblRx.rx.items(cellIdentifier: "RxCell", cellType: RxCell.self))  (row, element, cell) in
            //customise cell here
        
     .disposed(by: disposeBag)

【讨论】:

以上是关于无法使用 RxSwift 变量 asObservable() 设置绑定(到:UITableView)的主要内容,如果未能解决你的问题,请参考以下文章

RxSwift : BehaviorRelay 代替变量使用

RxSwift:使用 rx_refreshing 进行 uirefreshcontrol

RxSwift 正确使用变量

RxSwift 分页

RxSwift - Playground 执行失败:无法查找符号

使用 RxSwift/RxCocoa 制作的 TableView 在绑定到的变量中的数据更改后出现故障