我在一个项目中使用 RxSwift,其中我有一个带有不同 ViewItems
的 DataSource
。这是我的 DataSource
配置:
let dataSource = RxTableViewSectionedReloadDataSource<SectionedViewItem>(configureCell: { _, tableView, indexPath, item in
if let viewItem = item as? BannerViewItem {
guard let cell = tableView.dequeueReusableCell(withIdentifier: BannerCell.Key, for: indexPath) as? BannerCell else { fatalError() }
cell.configureBindings(itemSource: viewItem)
return cell
} else if let viewItem = item as? CarSpecificationViewItem {
guard let cell = tableView.dequeueReusableCell(withIdentifier: CarSpecificationCell.Key, for: indexPath) as? CarSpecificationCell else { fatalError() }
cell.configureBindings(itemSource: viewItem)
return cell
} else if let viewItem = item as? CarBenefitViewItem {
guard let cell = tableView.dequeueReusableCell(withIdentifier: CarBenefitCell.Key, for: indexPath) as? CarBenefitCell else { fatalError() }
cell.configureBindings(itemSource: viewItem)
return cell
} else if let viewItem = item as? FavoriteHeaderViewItem {
guard let cell = tableView.dequeueReusableCell(withIdentifier: CarFavoritesCell.Key, for: indexPath) as? CarFavoritesCell else { fatalError() }
cell.configureBindings(itemSource: viewItem)
return cell
} else {
return UITableViewCell()
}
})
然后我将它绑定(bind)到我的ViewModel
:
viewModel.dataSource.bind(to: tableView.rx.items(dataSource: dataSource)).disposed(by: disposeBag)
我通过以下方式订阅评选事件:
tableView.rx
.modelSelected(CarSpecificationViewItem.self)
.subscribe(tableViewRowSelected)
.disposed(by: disposeBag)
只要我只对 CarSpecificationViewItem
使用react,这种方法就可以正常工作。现在我已经为 CarFavoritesCell
激活了 userInteraction
并订阅了它的事件:
tableView.rx
.modelSelected(FavoriteHeaderViewItem.self)
.subscribe(test)
.disposed(by: disposeBag)
但这开始产生错误。点击我的 FavoriteHeaderViewItem 时发生崩溃:
Thread 1: Fatal error: Failure converting from Optional(CLCarRentalCore.FavoriteHeaderViewItem) to CarSpecificationViewItem
问题的根源可能是什么?提前致谢!
最佳答案
我解决了更高一级的问题并选择 ViewItemProtocol.self
作为我选择的模型,因为我所有的 ViewItems
都符合该协议(protocol)。我仍然不明白为什么我的问题的方法不起作用......
tableView.rx
.modelSelected(ViewItemProtocol.self)
.subscribe(onNext: { [weak self] viewItem in
switch viewItem {
case let item as CarSpecificationViewItem:
self?.carSpecificationSelected(for: item)
case is FavoriteHeaderViewItem:
self?.toggleLike()
default:
return
}
})
.disposed(by: disposeBag)
关于ios - Rx swift : Reacting to different cell types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53708356/