【问题标题】:How to observe previous and current value in RxSwift for UITableView tap/selection?如何在 RxSwift 中观察 UITableView 点击/选择的先前值和当前值?
【发布时间】:2017-12-19 00:56:43
【问题描述】:

我的UIViewController 中有以下代码:

  _ = viewModel.selectedCountryId.asObservable()
       .distinctUntilChanged()
        .scan((0, 0), accumulator: { (prev, curr) in
            return zip(prev, curr)
        })
        .subscribe(onNext: {
            let prevCell = self.tableView.cellForRow(at: IndexPath(row: previous, section: 0))
            prevCell?.accessoryType = .none
            let currCell = self.tableView.cellForRow(at: IndexPath(row: curr, section: 0))
            currCell?.accessoryType = .checkmark
        }).disposed(by: disposeBag)`

我不知道在 scan 上做什么,我相信通过查看一些 SO 帖子可以解决这个问题。

我想要实现的是选择一行并取消选择上一行,以使tableview具有右侧带有复选标记图标的单选机制。

我使用 viewModel 中的Variable<Int>,因为我需要保存我选择的行,以便在进行一些操作后将其传递给另一个视图控制器。

如有不妥之处,请多多指教。我仍然是 MVVM e RxSwift 的初学者。

编辑

这是选择项目时的订阅:

_ = tableView.rx.itemSelected.subscribe(onNext: { [weak self] indexPath in self?.viewModel.selectedCountryId.value = indexPath.row })

【问题讨论】:

    标签: ios iphone swift uitableview rx-swift


    【解决方案1】:

    对于这个用例,我更喜欢 zip 而不是扫描。

    Observable.zip(viewModel.selectedCountryId.asObservable(), viewModel.selectedCountryId.asObservable().skip(1)) {
      ($0, $1)
    }.subscribe(onNext: { [weak self] (previous, curr) in
      let prevCell = self.tableView.cellForRow(at: IndexPath(row: previous, section: 0))
      prevCell?.accessoryType = .none
      let currCell = self.tableView.cellForRow(at: IndexPath(row: curr, section: 0))
      currCell?.accessoryType = .checkmark
    }).disposed(by: disposeBag)
    

    Zip 将为每个 observables 组合发射。与第二个一样,我们跳过一个值,我们将获得以前的和当前的。 您可能希望在订阅之前添加一个 startWith 运算符,以便在最初选择的单元格上添加复选标记。

    绑定您的选择:

    tableView.rx.itemSelected.map { $0.row }.bind(to: self.viewModel.selectedCountryId).disposed(by: disposeBag)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-19
      • 1970-01-01
      • 2021-09-08
      • 2021-03-19
      • 1970-01-01
      相关资源
      最近更新 更多