ios - RxSwift : How to populate the data in collection view cell inside the table view using ViewModel?

标签 ios swift mvvm rx-swift

我确实有以下结构:

- 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/

相关文章:

ios - TestFlight 无法安装应用程序并且无法删除部分安装的应用程序

ios - Swift 3 - 第一个单元格已经展开的可展开表格 View 单元格

swift - 使用 View Swift 部分覆盖 UIStatusBar

wpf - WPF+MVVM+EF 6.1 的最佳模型

ios - viewDidAppear 和 viewDidLoad 初始化位置太晚了

ios - 在 iOS 上的 Swift 中从短 URL 获取完整 URL

ios - 带有静态表的动态类型和自调整单元格

ios - 用户信息中带有自定义对象的 UNMutableNotificationContent 使应用程序崩溃

c# - WPF 和 XAML 中的 OxyPlot LineAnnotation 可见性

c# - 当 DataContext 更改时,WPF ObservableCollection 尚未更新