Ali Baqbani
Ali Baqbani

Reputation: 153

Binding UIButton tap gesture in UITableViewCell to observable in viewModel

What is the best way to handle tap gesture of UIButton in UITableViewCell when working with RxSwift and MVVM pattern? Should I bind it to a variable in viewModel?

Upvotes: 0

Views: 3155

Answers (1)

Lio
Lio

Reputation: 4282

You could provide a tap observable in your cell and bind it from the vc.

class SomeCell: UITableViewCell {

    @IBOutlet var detailsButton : UIButton!


    var detailsTap : Observable<Void>{

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

    }
}

Then in the 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)

}

Upvotes: 5

Related Questions