将UITutView中的UIButton点击手势绑定到viewModel中的observable

问题描述 投票:0回答:1

在使用UIButton和MVVM模式时,在UITableViewCell中处理RxSwift的轻击手势的最佳方法是什么?我应该将它绑定到viewModel中的变量吗?

ios swift rx-swift
1个回答
4
投票

您可以在单元格中提供tap可观察并将其与vc绑定。

class SomeCell: UITableViewCell {

    @IBOutlet var detailsButton : UIButton!


    var detailsTap : Observable<Void>{

        return self.detailsButton.rx.tap.asObservable()

    }
}

然后在vc中:

private func bindTable(){
    //Bind the table elements
    elements.bind(to: self.table.rx.items) { [unowned self] (table, row, someModel) in
        let cell = cellProvider.cell(for: table, at: row) //Dequeue the cell here (do it your own way)

        //Subscribe to the tap using the proper disposeBag
        cell.detailsTap
            .subscribe(onNext:{ print("cell details button tapped")})
            .disposed(by: cell.disposeBag) //Notice it's using the cell's disposableBag and not self.disposeBag

        return cell
    }
        .disposed(by: disposeBag)

    //Regular cell selection    
    self.table.rx
           .modelSelected(SomeModel.self)
           .subscribe(onNext:{ model in print("model")})
           .disposed(by: self.disposeBag)

}
© www.soinside.com 2019 - 2024. All rights reserved.