1

我有一个带有 RxDataSources 的表格视图,其中单元格项目有一个删除图标。当单元格出列并单击该删除图标时,将触发所有先前的单击事件,从而重复点击。项目单元格:

 removeImageView.rx.tap().map { _ in indexPath } 
            .bind(to: viewModel.onRemoveItem).disposed(by: cellDisposeBag)

单元格视图模型:

let onRemoveItem = PublishSubject<IndexPath>()

单元格和 ViewModel 绑定的视图控制器视图模型:

 let vm = ItemViewModel(with: item)
            vm.onRemoveItem.bind(to: self.onRemoveItem).disposed(by: self.rx.disposeBag)

            return SectionItem.item(viewModel: vm)

视图控制器:

let dataSource = RxTableViewSectionedReloadDataSource<SectionItem>(configureCell: { dataSource, tableView, indexPath, item in
    switch item {
    case .item(let viewModel):
        let cell = (tableView.dequeueReusableCell(withIdentifier: itemtIdentifier, for: indexPath) as? ItemCell)!
        cell.bind(to: viewModel, at: indexPath)
        return cell
    }
}, titleForHeaderInSection: { dataSource, index in
    let section = dataSource[index]
    return section.title
}  )

output?.items
    .bind(to: tableView.rx.items(dataSource: dataSource))
    .disposed(by: rx.disposeBag)

output?.onRemoveCartIemTapped.distinctUntilChanged() 
    .skip(1)
    .distinctUntilChanged().drive(onNext: { [weak self] (indexPath) in
    print("onRemoveCartIemTapped" + String(indexPath.item))
}).disposed(by: rx.disposeBag)

控制台调试:

onRemoveCartIemTapped0
onRemoveCartIemTapped3
onRemoveCartIemTapped1
onRemoveCartIemTapped4
4

1 回答 1

2

这是由UITableView重复使用单元格引起的。为避免有多个订阅,您可以覆盖单元格的prepareForReuse()方法并确保处置任何现有订阅。

我通常将 声明DisposeBag为 var,然后DisposeBagprepareForReuse(). 当DisposeBag被取消时,它将处理它包含的所有订阅。就像是:

override func prepareForReuse() {
    super.prepareForReuse()

    cellDisposeBag = DisposeBag()
}
于 2019-01-03T09:15:02.637 回答