首页 > 解决方案 > 如何使用 mvvm 处理独特的单元格操作

问题描述

我在 UITableView 中有一个独特的单元格,它有两个按钮。我需要将这些操作绑定到控制器的 viewModel。我以这种方式将视图与视图模型绑定:

func attach(wrapper: Attachable<ViewModel>) -> ViewModel {
    self.viewModel = wrapper
    loadViewIfNeeded()
    let viewModel = self.viewModel.bind(bindings: bindings)
    return bind(viewModel: viewModel)
}

因此,当调用 loadViewIfNeeded() 方法时,我仍然没有来自数据源的任何单元格。这就是为什么我不能从单元格的按钮创建绑定。

我尝试以这种方式使用委托和关联,但我认为我错过了更好的解决方案:

protocol ProfileActionsViewCellDelegate {
     var addFriendButton: UIButton { get }
}

单元格内的代码

func bind(to viewModel: ProfileActionsViewModel) {
    addFriendButton.rx.tap
        .do(onNext: { [unowned self] _ in self.delegate?.addFriendButton.sendActions(for: .touchUpInside) })
        .debug()
        .subscribe()
        .disposed(by: disposeBag)
}

mvvm 配置文件示例

标签: iosswiftmvvmrx-swift

解决方案


推荐阅读