我确实有以下结构:
- TableView
-- Custom Table View Cell
--- CollectionView
---- Custom CollectionView Cell
我想了解如何使用 RxSwift - MVVM 结构从/使用此结构中的 View 模型传递数据。
每当我从 API 得到响应时,它应该分别更新表 View 行和关联的集合 View 单元格中的数据。
最佳答案
最简单的解决方案是使用数组数组。
例如。让我们假设您的 API 返回:
struct Group: Decodable {
let items: [String]
}
那么你的 View 模型就会像这样简单:
func tableViewItems(source: Observable<[Group]>) -> Observable<[[String]]> {
return source
.map { $0.map { $0.items } }
}
创建单元格时,您可以使用
Observable.just()
将内部数组包装成一个可观察对象。像这样:// in your view controller's viewDidLoad for example.
tableViewItems(source: apiResponse)
.bind(to: tableView.rx.items(cellIdentifier: "Cell", cellType: CollectionTableViewCell.self)) { _, element, cell in
Observable.just(element)
.bind(to: cell.collectionView.rx.items(cellIdentifier: "Cell", cellType: UICollectionViewCell.self)) { _, element, cell in
let label = (cell.viewWithTag(6969) as? UILabel) ?? UILabel()
label.tag = 6969
label.text = element
label.sizeToFit()
cell.addSubview(label)
}
.disposed(by: cell.disposeBag)
}
.disposed(by: dispsoeBag)
关于ios - RxSwift : How to populate the data in collection view cell inside the table view using ViewModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61287894/