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

时间:2017-12-12 12:13:53

标签: ios swift rx-swift

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

1 个答案:

答案 0 :(得分: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)

}