iOS Swift:不使用RxCocoa的TableView数据源



晚上,在我的应用程序中,我不想使用RxCocoa,我正在努力遵守表视图数据源和委托,但我遇到了一些问题。

如果不使用RxCocoa或RxDataSource,我找不到任何指南。

在我的ViewModel中,有一个lazy computed var myData: Observable<[MyData]>,我不知道如何获取行数。

我想把可观察到的转化为Bheaviour主题,然后得到它的值,但我真的不知道做这个的最佳实践是什么

您需要创建一个符合UITableViewDataSource和Observer的类。一个快速而肮脏的版本看起来像这样:

class DataSource: NSObject, UITableViewDataSource, ObserverType {
init(tableView: UITableView) {
self.tableView = tableView
super.init()
tableView.dataSource = self
}
func on(_ event: Event<[MyData]>) {
switch event {
case .next(let newData):
data = newData
tableView.reloadData()
case .error(let error):
print("there was an error: (error)")
case .completed:
data = []
tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = data[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
// configure cell with item
return cell
}
let tableView: UITableView
var data: [MyData] = []
}

将此类的实例作为视图控制器的属性。将您的myData绑定到它,如:

self.myDataSource = DataSource(tableView: self.tableView)
self.myData
.bind(to: self.myDataSource)
.disposed(by: self.bag)

(我把所有的self都放在上面,以使事情变得明确。)

您可以将其细化到有效地重新实现RxCoca的数据源,但这有什么意义?

最新更新