问题描述
我有一个tableView
,其中有两个cells
:StaticSupportTableViewCell
和SupportTableViewCell
。顾名思义,第一个cell
是tableView
顶部的单个静态单元格。 SupportTableViewCell
可以是任何数字,应显示在静态cell
下方。
viewmodel.multiContent.bind(to: tableView.rx.items) { tableView,index,item in
if let cellviewmodel = item as? StaticSupportTableViewCellviewmodel {
let cell = tableView.dequeueReusableCell(withIdentifier: StaticSupportTableViewCell.identifier) as? StaticSupportTableViewCell
cell?.viewmodel = cellviewmodel
guard let guardedCell = cell else { return UITableViewCell()}
return guardedCell
}
if let cellviewmodel = item as? SupportTableViewCellviewmodel {
let cell = tableView.dequeueReusableCell(withIdentifier: SupportTableViewCell.identifier) as? SupportTableViewCell
cell?.viewmodel = cellviewmodel
guard let guardedCell = cell else { return UITableViewCell()}
return guardedCell
}
else { return UITableViewCell() }
}.disposed(by: disposeBag)
在viewmodel
中,我有一个multiContent
变量:
var multiContent = BehaviorRelay<[Any]>(value: [])
现在,如果我一个接一个地接受cell
viewmodels
到它,它将起作用:
这有效:
multiContent.accept([StaticSupportTableViewCellviewmodel(myString: "TESTING")])
或者这样做:
multiContent.accept(mainService.serviceProviders.compactMap { SupportTableViewCellviewmodel(serviceProvider: $0,emailRelay: emailRelay)})
但是,如果我同时尝试...
multiContent.accept([StaticSupportTableViewCellviewmodel(myString: "TESTING")])
multiContent.accept(mainService.serviceProviders.compactMap { SupportTableViewCellviewmodel(serviceProvider: $0,emailRelay: emailRelay)})
...仅显示最后一个单元格。就像最后一个替换第一个而不是添加一个。
那么我如何将cell
viewmodels
都接受到中继中,以便两者都显示在tableView
中?
编辑
我通过将两个cell
viewmodels
添加到一个array
中来解决这个问题:
let contents: [Any] = [StaticSupportTableViewCellviewmodel(brand: name,url: web.localized(),phoneNumber: phone.localized()),mainService.serviceProviders.compactMap { SupportTableViewCellviewmodel(serviceProvider: $0,emailRelay: emailRelay)}]
并更改了binding
:
if let cellviewmodels = item as? [SupportTableViewCellviewmodel] {...
这是个问题,尽管我坚持使用array
和[SupportTableViewCellviewmodel]
中的cells
。当它们相互覆盖时,循环循环并返回cell
无效。
解决方案是发送viewmodel
SupportTableViewCellviewmodel
[SupportTableViewCellviewmodel]
而不是module conv ( .array(io),.a(io[1]),.b(io[0]) );
inout [1:0] io;
endmodule
,但是我该怎么做?
解决方法
BehaviorRelay仅发出接受的最新数组。调用accept(_:)
时,您没有添加中继的状态,而是要替换其状态。要同时发射这两个数组,您需要将两个数组连接起来。
通常,应避免在生产代码中使用中继和主题。它们对于学习Rx系统和样本非常有用,但是在现实世界中很难找到正确的方法。仅在将非Rx代码转换为Rx或设置反馈循环时才需要它们。
此外,主题,中继或可观察对象也不应该是var
。您不想一次更换一个。将它们设置为let
。